Skip to main content

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



Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...