Quiz Entry - updated: 2026.07.10
What's the difference between << (left shift) and >> (right shift)?
x << n shifts bits left (multiply by 2ⁿ) filling with zeros; x >> n shifts right (divide by 2ⁿ) — and the caveat is that right-shifting a signed negative value is implementation-defined.
Left shift <<:
// Shift bits left by n positions, fill with 0s
x << n
// 0101 → 1010 (×2)
5 << 1 = 10
// 0101 → 10100 (×4)
5 << 2 = 20
// Quick power of 2
1 << n = 2ⁿ
Right shift >>:
// Shift bits right by n positions
x >> n
// 10100 → 1010 (÷2)
20 >> 1 = 10
// 10100 → 101 (÷4)
20 >> 2 = 5
Signed vs unsigned right shift:
// Unsigned: logical shift (fill with 0s)
unsigned int u = 0x80000000;
// 0x40000000
u >> 1;
// Signed: arithmetic shift (fill with sign bit) - implementation-defined!
// -2147483648
int s = 0x80000000;
// 0xC0000000 (-1073741824) on most systems
s >> 1;
Common uses:
// Create mask for bit n
1 << n
// Extract bit n
x >> n & 1
// Combine bytes
x << 8 | y
// Fast divide by power of 2
x / 8 ≡ x >> 3
// Fast multiply by power of 2
x * 16 ≡ x << 4