Bitwise Operators

    Sometimes, it is more feasible to perform bit by bit operations, especially for performance boost in graphics rendering, in machine level communication, and even in communication via network. Recall that 0 signifies false and 1 signifies true, therefore, 0 and 1 are called truth values. Practically, at machine level, 0 is represented by low voltage and 1 is represented by high voltage. Let us see what happens when we apply bitwise operators on these truth values.

A
B
A&B (A AND B)
A|B (A OR B)
A^B (A XOR B)
~A (NOT A)
0
0
0
0
0
1
0
1
0
1
1
1
1
0
0
1
1
0
1
1
1
1
0
0

This table illustrates bit wise operation at a single bit level. At a higher level (8-bit, 16-bit etc. ), bitwise operations are as follows:
    35 in 8-bit representation - 0010 0011
    18 in 8-bit representation - 0001 0010
    35 & 18 - 0000 0010 (i.e, 2)    

Here is a code example that illustrates all the Bitwise operators.

#include <stdio.h>

int  main() 
{

    int a = 35;   
    int b = 18; 
              
    printf (" a & b  =  %d\n", a & b );
    
    printf (" a | b  =  %d\n", a | b );
    
    printf (" a ^ b  =  %d\n", a ^ b );
    
    printf (" ~a  =  %d\n", ~a ); 
    
    printf (" a << 1  =  %d\n", a << 1);
 
    printf (" a >> 1  =  %d\n", a >> 1);    


}

Output:



>> and << were not mentioned before, because their operation is a bit different from &, | and ^. However, they are quite simple. These operators are called Shift operators. << for Left Shift and >> for Right Shift.
35 << 1 tells the compiler to shift all the bits (in bit-level representation of 35) towards the left by 1 step. So 0010 0011 << 1 returns 0100 0110 which is 70
Similarly, 0010 0011 >> 1 returns 0001 0001 which is 17 (By shifting all bits of 35 towards right by 1 step). You can experiment by using some other number instead of 1.
During shifting, the spaces are filled by zeroes.


An interesting thing to note here is, Left shift by 1 step Multiplies the number by 2 and Right shift by 1 step Divides the number by 2.
Therefore, result of 35 << 1 is same as 35 * 2 i.e 70, and result of 35 >> 1 is same as 35 / 2 i.e, 17 (integer division). 

Generalized formulae:

  • For Left shift - a << b = a * pow (2, b)
  • For Right shift - a >> b = a / pow (2, b)
Here, pow(); is an inbuilt function available in header file <math.h>, which results '2 raised to power b'

The next Section will discuss about reaming operators.



Previous
Next Post »