Skip to content

Bitwise Shift operator in Python

  • by

Python Bitwise shift operators are binary operators. It is used to shift bits of a binary representation of a number to left or right by specific places.

>>Bitwise right shiftx>>
<<Bitwise left shiftx<<

Bitwise shift operators are often used for operations in which we have to multiply or divide an integer by powers of 2.

  • << (left shift): This operator shifts the bits of the left-hand operand to the left by the number of positions specified by the right-hand operand. In other words, it effectively multiplies the left-hand operand by 2right operand2right operand.
  • >> (right shift): This operator shifts the bits of the left-hand operand to the right by the number of positions specified by the right-hand operand. In other words, it effectively divides the left-hand operand by 2right operand2right operand.

Shift operator in Python

Simple example code.

Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left ( fills 1 in the case of a negative number). Similar effect to dividing the number with some power of two.

n1 = 14
n2 = 2

res  = n1 >> n2

print("Operand 1 is:", n1)
print("operand 2 is:", n2)

print("Result of the right shift operation on {} by {} bits is {}.".format(n1, n2, res))

Output:

Bitwise Right Shift Operator in Python

Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids right. Similar effect to multiplying the number with some power of two.

n1 = 14
n2 = 2

res = n1 << n2

print("Operand 1 is:", n1)
print("operand 2 is:", n2)

print("Left shift operation on {} by {} bits is {}.".format(n1, n2, res))

Output:

Bitwise Left Shift Operator in Python

Do comment if you have any doubts or suggestions on this Python 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

Your email address will not be published. Required fields are marked *