<< Bitwise Left Shift in Python

Hi Python Buddies,

Hope you are doing well.

I would like to clear the general confusion caused during the understanding of the Bitwise Left Shit(<<).

Before understanding the Bitwise Left shift, we need to understand the basics of Binary Notation of decimal Number system that we use.

In the above table, you can see that to represent the number from 0-15, 4 bits are enough; whereas to represent the numbers from 16-20 we need an extra bit(5th bit).

I hope you are all aware of how to convert the given decimal number to the binary number.

Now let's understand the Bitwise Left Shift(<<)

x1 = 3
x1 = x1 << 2   #This means, 3 is Left bit shifted 2 times
print(x1)


x2 = 3
x2 <<= 2     #This also means, 3 is Left bit shifted 2 times
print(x2)

the output is:
12
12

Let's understand how the output gets to 12.

The 4-bit Binary equivalent of 3 in our example is 0011.

Bitwise left shift n times meaning, we have to remove n most significant bits and add n number of zero's(0) to the right of the given binary number.

In our example, n is 2 so we need to remove 2 most significant bits(00 in our case) and add 2 zeros to the right of 3(0011) which will become 1100.

If we convert the result(1100) to decimal format then the result is 12. This is the reason why our output is 12.

NB: The above is the way the computer does it. As humans, we like to do things the easy way, below explains the easy way.

We just have to multiply 3 by 2^n. In our example, n is 2 so, 3 * 2^2 = 12.

NB: Most significant bits = Right Most bits in a given binary number

Comments