A quick primer on bit-wise and bit-shift operators


Bit-wise operators (|, &, ^, ~, |=, &=, ^=, ~=) and bit-shift operators (<<, >>, <<=, >>=) only work on limited types; which are int and char (and variations of int):

AND ‘&’
xi
 yi   
 xi & yi
0
0
0
0
1
0
1
0
0
1
1
1

OR ‘|’
xi
 yi   
 xi | yi
0
0
0
0
1
1
1
0
1
1
1
1

XOR ‘^’
xi
 yi   
 xi ^ yi
0
0
0
0
1
1
1
0
1
1
1
0

NOT ‘~’
xi   
~xi
0
1
1
0

LEFT-SHIFT ‘<<’
Suppose x is a 8-bit unsigned with following bit-values:
b7 
b6 
b5 
b4 
b3 
b2 
b1 
b0
1
1
0
0
0
1
1
1
Then x<< 3 will be (shift the bits toward left by 3 bit):
b7 
b6 
b5 
b4 
b3 
b2 
b1 
b0
0
0
1
1
1
0
0
0
When there is no overflow (no fall off the bit on left edge), shifting ‘n’ bits of number ‘x’ towards left is equivalent to multiplying the x by 2n.

RIGHT-SHIFT ‘>>’
Suppose x is a 8-bit unsigned with following bit-values:
b7 
b6 
b5 
b4 
b3 
b2 
b1 
b0
1
1
0
0
0
1
1
1
Then x>> 3 will be (shift the bits toward right by 3 bit):
b7 
b6 
b5 
b4 
b3 
b2 
b1 
b0
0
0
0
1
1
0
0
0
Shifting ‘n’ bits of number ‘x’ towards right is equivalent to dividing the x by 2n.

Have fun with following piece of code:
 
#include <stdio.h>

int main()
{
            // SWAP the values
            int x= 12, y= 66;
            printf("Before SWAP: x = %d, y = %d\n", x, y);
            x^=y;
            y^=x;
            x^=y;
            printf("AFTER SWAP: x = %d, y = %d\n", x, y);


            // LEFT-SHIFT operator
            x = 3;
            y = 2;
            printf("\nBefore LEFT-SHIFT: x = %d, y = %d\n", x, y);
            x << y ;
            printf("After LEFT-SHIFT(\?\?): x = %d, y = %d\n", x, y);
            printf("\nBefore LEFT-SHIFT: x = %d, y = %d\n", x, y);
            x <<= y ; // x = x << y
            printf("After LEFT-SHIFT(Observe x * 2*2): x = %d, y = %d\n", x, y);


#define FIRST_BIT 0x1
#define SECOND_BIT 0x2
#define THIRD_BIT 0x4
#define FOURTH_BIT 0x8
#define GET_BIT(X,WHICH_BIT) (WHICH_BIT & X? true: false)

            x = 10;
            printf("\nBit values of x (=%d) is %d %d %d %d\n", x,
                                    GET_BIT(x, FOURTH_BIT),
                                    GET_BIT(x, THIRD_BIT),
                                    GET_BIT(x, SECOND_BIT),
                                    GET_BIT(x, FIRST_BIT));
            return 0;
}


A quick primer on bit-wise and bit-shift operators A quick primer on bit-wise and bit-shift operators Reviewed by Sourabh Soni on Sunday, August 12, 2012 Rating: 5

No comments

Author Details

Image Link [https://3.bp.blogspot.com/-zo21XIdyPqc/VuTrFfUyPhI/AAAAAAAAAO8/EEWTN73XHUA7aTIjuxuBSN-WGaGkNUymA/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]