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



Both the left shift and right shift are known as bitwise shift operators. These operators are useful for working with binary integers by shifting the bits to the left or right.

Below is the mathematical representation of the left and right shift operators:

// left shift operator
x << n means (x * 2n)

// right shift operator
x >> n means (x/2n)

What is Left Shift Operator?

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

Syntax

The basic syntax of left shift operator as follows:

<<

Example

In this example, we demonstrate the left shift operation on an integer and then multiply the number 28 by the power of 2 from 20 to 23 and display the result of a particular shift.

Here, you can see how for loop iterating the calculation of the left shift operator over integer:

when i = Expression Operation Result (Decimal) Binary Result
0 28 << 0 28 * 20 28 00011100
1 28 << 1 28 * 21 56 00111000
2 28 << 2 28 * 22 112 01110000
3 28 << 3 28 * 23 224 11100000
C C++
#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

The above program produces the following result:

Left shift by 0: 28
Left shift by 1: 56
Left shift by 2: 112
Left shift by 3: 224
#include <iostream>
using namespace std;

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

   for (i; i <= 3; ++i)
       cout << "Left shift by " << i << ": " << (y << i) << endl;

   return 0;
}

Output

The above program produces the following result:

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

What is Right Shift Operator?

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

Syntax

The basic syntax of right shift operator as follows:

>>

Example

Below the program uses the right shift operator to divide the given number 10 by a power of 2 when i = 0 (for loop). Next, right shift divides the number by 2i, thus, it results 10 >> 0 = 10 and 10 >> 1 = 5.

C C++
#include <stdio.h>

int main() {

   // binary value of 10 is 1010
   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

The above program produces the following result:

Right shift by 0: 10
Right shift by 1: 5
#include <iostream>
using namespace std;

int main() {

   // binary value of 10 is 1010
   int x = 10; 
   int i = 0;

   // Loop to perform right shift by 0 and 1
   for (i; i < 2; i++)
       cout << "Right shift by " << i << ": " << (x >> i) << endl;

   return 0;
}

Output

The above program produces the following result:

Right shift by 0: 10
Right shift by 1: 5
Updated on: 2025-05-02T18:02:48+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements