Bitwise operators

C is a small language. It has just 32 keywords. But it has a rich set of operators.

The operators which are commonly not used are bitwise operators. Here C comes closer to Assembly language because it lets you manipulate individual bits of a number.

Let us look at some examples.

int a,b,c;
a = 10;
b = 12;
c = a|b;

Here | is bitwise OR operator. Individual bits of a and b are ORed and result is stored in c. 

a = 00001010
b = 00001100
c = 00001110

So c will be 14

A small summary of bitwise operators here


Operator Description Example
& AND - If both bits are 1, result is 1. If not result is 0 10&4 is 1010 | 0100 = 0000
| OR- If either bit is 1, result is 1. If not result is 0 10|4 is 1010 |0100 = 1110 = 14
^ EXOR - If either bits are 1, but not both, result is 1. If not result is 0 10^4 is 1010 ^ 0100 = 1110 10^8 is 1010 ^1000 = 0010 = 2
<< LEFT SHIFT - Shifts bits by n places to the left, adding 0 in empty bits 10<<2 101000="40</td" 1010="">
>> RIGHT SHIFT - Shifts bits by n places to the right adding 0 in empty bits 10<<2 101000="40" 1010="" are="" beyond="" bits="" lost="" lsb="" shifted="" td="">
>> COMPLEMENT Complements all the bits. i.e. 1 to 0 and 0 to 1 ~10 is 11110101 for unsigned char (1 byte)


Shift Operators

Left shift - <<, shifts all bits of a number to left by given number of bits. The empty bits in LSB are filled with 0.

e.g.

a = 10;
b = a<<2;

a = 00001010;
b = 00101000;

So b will be 40.

>> shifts all bits of the number to right by given number of bits. The bits pushed beyond LSB are lost.

a = 10;
b = a>>2;

000010101 >> 2 = 00000010 

b becomes 2.

As you might have guessed, left shift operator multiplies the number by 2 to the power of n 

Right shift divides the number by 2 to the power of n.

|=, &= and other operators

And arithmetic assignment operator, there are bitwise assignment operators.

|=      &=        ^=        <<=      >>= 

a |=b ; 
is equivalent to a = a|b;

Now time for some small program.


 #include<stdio.h>  
 int main()  
 {  
   int a =10;  
   int b = 1;  
   int c;  
   c = a|b;  
   printf("OR %d\n",c);  
   c = a&b;  
   printf("AND %d\n",c);  
   c = a^b;  
   printf("EXOR %d\n",c);  
   c = a<<b;  
   printf("Left shift %d\n",c);  
   a >>=b;  
   printf("right shift= %d\n",a);  
   c = ~b;  
   printf("complement of b%d\n",c);   
 }  

Comments

Popular Posts