home · notes

Bit-shift operator

Easier to understand with examples:

# Binary: 00000101
x = 5

# Shift left by 2 positions
y = x << 2

# After shifting left by 2 positions, y will be:
# Binary: 00010100
# Decimal: 20

print(y)  # 20
# Binary: 00010100
x = 20

# Shift right by 2 positions
y = x >> 2

# After shifting right by 2 positions, y will be:
# Binary: 00000101
# Decimal: 5

print(y)  # 5