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


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

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements