Shift Bitwise Operations

Basic

Left Bit Shift

Assume we want to left bit shift the binary 0100 as below.

0100 -> 1000

We can achieve this using the << operator in Python.

0b100 << 1
# 8 ('1000' in binary)

4 << 1
# 8 ('1000' in binary)

# Output as the binary representation
bin(8 << 1)
# 0b1000

Right Bit Shift

Assume we want to right bit shift the binary 0100 as below.

0100 -> 0010

We can achieve this using the >> operator in Python.

0b100 >> 1
# 2 ('10' in binary)

4 >> 1
# 2 ('10' in binary)

bin(4 >> 1)
# 0b10