What are the >> and << operators in Python?

PythonServer Side ProgrammingProgramming

The symbols << and >> are defined as left and right shift operators respectively in Python. They are bitwise operators. First operand is a bitwise representation of numeric object and second is the number of positions by which bit formation is desired to be shifted to left or right.

The << operator shifts bit pattern to left. The least significant bits on right are set to 0

>>> a=60
>>> bin(a)
'0b111100'
>>> b=a<<2
>>> b
240
>>> bin(b)
'0b11110000'

You can see two bits on right set to 0

On the other hand >> operator shifts pattern to right. Most significant bits are set to 0

>>> a=60
>>> bin(a)
'0b111100'
>>> b=a>>2
>>> b
15
>>> bin(a)
'0b111100'
raja
Published on 14-Feb-2018 16:13:48
Advertisements