Why Shifting Right Is Not the Same as Dividing
Subtitle: They agree on positives. Not on signs.
Left column - Logical shift (unsigned):
Zeros always enter at the top Sign bit is just another bit 249 >> 1 becomes 124 Made for flags and unsigned math Java writes this one as >>>
Right column - Arithmetic shift (signed):
Copies the sign bit inward A negative stays negative -7 >> 1 becomes -4 Why two machine instructions exist Java writes this one as >>
Simple difference:
Divide rounds toward zero Shift rounds toward minus infinity
Rounding - where they split:
Both throw away the low bits Divide drops the remainder Shift keeps the floor of the value They differ on every negative odd
- Honest test - three steps:
- Print -7 / 2 and -7 >> 1
- One gives -3, one gives -4
- Repeat with -5, -9 and -11
Sticky note - Common beginner mistake:
Treating >> as a fast divide for signed values. In C a right shift of a negative was implementation-defined before C++20, and shifting by the type width or more is undefined behaviour.