educative.io

Educative

Please elaborate the left and right shift

In computers, all numbers are stored as bytes (set of bits). These byte representations are made up of 1s and 0s known as bits. So, let’s take the binary representation of 20, which is 00010100.

Right-shift would shift all the bits to the right. This way, the right-most bit will be lost since all the bits have shifted. The result would be 00001010. Performing a right-shift again would give us 00000101. In Python, if we do num1 >> 3, this is equivalent to performing the right-shift 3 times.

The left-shift works in the same way except that it moves all the bits to the left. Furthermore, a 0 takes the place of the right-most bit that has now moved to the left. So, for 00010100, a left shift would be 00101000, and so on.

1 Like