Bit Shifting
Shifting moves the bits of a value left or right, multiplying or dividing by powers of two.
Left shift
A left shift by k moves every bit k places toward the high end, filling the low bits with zeros. For values that do not overflow, this multiplies by 2ᵏ: 3 << 2 equals 12.
Right shift
A right shift by k moves bits toward the low end. For unsigned values it fills the high bits with zeros and divides by 2ᵏ, discarding any remainder. So 13 >> 1 equals 6.
Logical versus arithmetic right shift
For signed values, an arithmetic right shift copies the sign bit into the vacated high bits, preserving the sign; a logical shift fills with zeros. Languages differ in which they apply, so signed right shifts need care.
Uses
- Fast multiply or divide by powers of two
- Packing several fields into one integer
- Extracting a bit range with shift then mask
- Building bit masks such as 1 << n
Cautions
Shifting by a count greater than or equal to the word width is undefined or platform-dependent in many languages. Left-shifting into or past the sign bit can also cause overflow or unexpected sign changes.
print(3 << 2) # 12
print(13 >> 1) # 6
print((-8) >> 1) # -4 in Python (arithmetic)