Menu
Coddy logo textTech

Right and left shift operators

Lesson 7 of 17 in Coddy's Bit Manipulation course.

Shift operators are used to shift bits towards either left or right. 

Right shift operator ( >> )

It takes two operands. The first value is the number whose bits we want to shift rightwards and the second operand is how many positions we want to shift. Basically we push zeroes from the MSB side of the number into the binary number.

Right shift is denoted as '>>' . 

Right shift is equivalent to dividing the number by a power of two. Let's understand it using an illustration.

We have taken (11)10 and have shifted it towards right 3 times which gave us (1)10 as output. We can also calculate it by taking floor of (11 / 23) which is nothing but (1)10.  

Usage:

int a = 11;
a>>3;
OUTPUT: 1

Here a is the number whose bits have to be shifted and 3 is the number of positions to shift to right for the given number.

Left shift operator ( << )

It also takes two operands. The first operand is the number whose bits we want to shift leftwards and the second operand is how many positions we want to shift. Basically we push zeroes from the LSB side of the number. Left shift is denoted as '<<' . Left shift is equivalent to multiplying the number by a power of two. Let's understand it using the same example.

We have taken (11)10 and have shifted it towards right 3 times which gives us (88)10 as output. We can also calculate it by multiplying (11)10 by 23 which is (88)10. Note one thing here that we cannot remove the MSB in this case, left shifting will increase the bit and push zeroes from LSB side but it will not remove the MSB bits. While in case of right shift we push zeroes from the MSB side and the bits to the left are simply omitted.

Usage:

int a = 11;
a<<3;
OUTPUT: 88
challenge icon

Challenge

Easy

Double the given number (the input) using shift operators.

Try it yourself

#include <iostream>
#include <vector>
using namespace std;

int Double(int num) {
    // Write code here
}

All lessons in Bit Manipulation