Left Shift and Right Shift Operators in C/C++

C++ProgrammingServer Side Programming

Left Shift

In the left shift operator, the left operands value is moved left by the number of bits specified by the right operand.

Here is an example of left shift operator in C language,

Example

 Live Demo

#include <stdio.h>

int main() {
   int y = 28; // 11100
   int i = 0;

   for(i;i<=3;++i)
   printf("Left shift by %d: %d\n", i, y<<i);

   return 0;
}

Output

Here is the output

Left shift by 0: 28
Left shift by 1: 56
Left shift by 2: 112
Left shift by 3: 224

Right Shift

In the right shift operator, the left operands value is moved right by the number of bits specified by the right operand.

Here is an example of right shift operator in C language,

Example

 Live Demo

#include <stdio.h>

int main() {
   int x = 10; // 1010
   int i = 0;

   for(i;i<2;i++)
   printf("Right shift by %d: %d\n", i, x>>i);

   return 0;
}

Output

Here is the output

Right shift by 0: 10
Right shift by 1: 5
raja
Published on 24-Oct-2018 13:59:53
Advertisements