Wednesday, July 10, 2013

Shift Operators in C

Shift Operators are bit-wise operators used to shift the bits of a number either two the left or to the right. Based on the side which we are shifting, shift operators are classified into two types.

  1. Left Shift(<<)
  2. Right Shift(>>)
Both these Operators considers the binary representation of the number and shift the bits.

Left Shift: 

Left Shift Operator is represented by <<. It shifts the bits to the left side. 

For example, if we write
x=3<<1
It means that shift the bits of 3 by 1 position.
Then it takes the binary representation of 3, which is 011. Shifting 1 bit to the left gives the value as 110 which is 6. Thus left shift operator is used to double the given value.

If we write 3<<2, then it moves the bits of 3 two times and hence the result becomes as 12.

Right Shift:  

Right Shift Operator is represented by >>. It shifts the bits to the right side.

For example, if we write 
x=3>>1
It means that shift the bits of 3 to right by 1 position.
The binary representation of 3 is 011. To right shift 3 by 1, we get the result as 001 which is 1, nothing but integer value of half the number. Hence Right Shift is used to reduce the number to half.

If we represent 8>>2, then it moves bits of 8 two times and the value becomes 2.

Note:This operator doesn't change the value of a, they just give the result with a shift.

Consider the following program, to understand the shift operators clearly,


  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=5;
  5. printf("Program to know whether given number is even or odd");
  6. if(a==(a>>1)<<1)
  7. printf("It is a even number");
  8. else
  9. printf("It is a odd number");
Try out the above program, you will understand the shift operators clearly.