Skip to content

Bitwise Left shift operator in Python

  • by

Python Bitwise Left shift operator is used to shift the binary sequence to the left side by a specified position. if you have a number 14.

x << n

The Binary representation of 14 is 00001110 (for the sake of clarity let’s write it using 8-bit)

14 = (00001110) 2

Then 14 << 1 will shift the binary sequence 1 position to the left side.

Left shift operator in Python

Simple example code bitwise left-shift operator to integer 32 shifting it by one position.

x = 32
# Shift by one position to the left
res = x << 1
print(res)

# Shift by two positions to the left
res = x << 2
print(res)

Output:

Left shift operator in Python

The bit representation of decimal 32 is "0100000". If you shift it by one position to the left, you obtain binary "01000000" (decimal 64). If you shift by two positions to the right, you obtain binary "010000000" (decimal 128).

Do comment if you have any doubts or suggestions on this Python bitwise operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading