In Python, the shift operators are used to move bit patterns either to the left or to the right. The shift operators are represented by the symbol < and > and are used in the following form:
Left shift: op<<n
Right shift: op>>n
Here op is the integer expression that is to be shifted, and n is the number of bit positions to be shifted. There are two restrictions on the value n. It may not be negative and may not exceed the number of bits used to represent the left operand op.
In the left-shift operation, all the bits in the operand op are shifted to the left by n position. The leftmost n bits in the original are removed, and the rightmost n bit positions that are vacated are filled with 0s.
For example, suppose we have x=0001 1101, then x<<1 gives result=0011 1010
Python left-shift operation example:
A=90 B=A<<1 print(B)
Output:
180
In the right-shift operation, all the bits in the operand op are shifted to the right by n position. The rightmost n bits in the original are removed, and leftmost n bit vacated positions are filled with 0s.
For example, suppose we have x=0001 1101, then x>>1 gives result=0000 1110
Python right-shift operation example:
A=90 B=A>>1 print(B)
Output:
45
Leave a comment