Bitwise shift operators with example

There are two types of shift operators.  They are
1. Left shift operator (<<)
2. Right shift operator(>>)

Left shift operator:
It is used to shift the bits of the first operand to left by the number of bit places the second operand specifies.

Example: 2 << 4
Binary value of 2 is 00000010
00000010 << 4 is 00100000
Decimal value of 00100000 is 32

Right shift operator:
It is used to shift the bits of the first operand to right by the number of bit places the second operand specifies.

Example: 32 >> 4
Binary value of 32 is 00100000
00100000 >> 4 is 00000010
Decimal value of 00000010 is 2

Example C program on bitwise shift operators
 
#include <stdio.h>
int main() {
int x = 2, y = 4, res;
res = x << y; // left shift x by y
printf("%d << %d is %d\n", x, y, res);
x = res;
res = x >> y; // right shift x by y
printf("%d >> %d is %d\n", x, y, res);
return 0;
}


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  02 << 4 is 32
  32 >> 4 is 2



Bitwise shift operators with example Bitwise shift operators with example Reviewed by Mursal Zheker on Minggu, Desember 29, 2013 Rating: 5

Tidak ada komentar:

Diberdayakan oleh Blogger.