Pages1

Rounding up a number to power of 2 < number

Using concept of "n&(n-1)" makes value = 0 if n is number with power of 2

#include <stdio.h>
int nextPwrOf2(int num)
{
     do
     {
 

Rounding up a number to next power of 2.

By using the concept of filling all the bits by 1 using shift operation. 
---------------------------------------------------------------------
#include<stdio.h>
int main()
{
      unsigned int n =1;
      n |= n >> 1;
      n |= n >> 2;

C programming :Handy Bitwise Expressions

Index
Expression
Purpose
Remarks
1
X & 1
Check whether number
is odd or even
All numbers are interms of 0’s and 1’s and hence it is sufficient check the last bit
2
X << 1
Multiply by 2

3
X >> 1
Divide by 2( Integer Division

4
~X+1
Negative the number
Negative numbers are represented by two complement. (one’s complement +1)
5
X ^ all’ones
Bit toggling (equivalent
to ~)

6
X >> 31
To find out the sign of number X.

Result is 0 or 1 based on the sign.
7

Mask = (X-Y) >> 31

Result = (Mask & X) | (~Mask & Y)
Min(X, Y) without using
comparisons
Mask contains all zeros if Y is less than or equal to X and all ones if X is less than Y.
8

Mask = (X-Y) >> 31

Result = (Mask & Y) | (~Mask & X)
Max(X, Y) without using comparisons
Mask contains all zeros if X is greater than or equal to Y and all ones if Y is greater than X.

C Program to reverse bits in character, integer; function to print bits of a character integer

#include<stdio.h>
void printBits(unsigned int num)
{
        char bit =0;
        for(bit=0;bit<(sizeof(unsigned char) * 8); bit++)
        {