Right Shift as Divide by 2
Learn how right shifting (>>) divides by 2^N. Understand the difference between arithmetic (>>) and logical (>>>) right shifts for signed numbers.
Detailed Explanation
Right Shift (>>) as Division
Shifting a binary number right by one position is equivalent to integer division by 2. Shifting right by N positions divides by 2^N (with truncation toward negative infinity for signed values).
How It Works
40 = 00101000
40 >> 1 = 00010100 (20, which is 40 / 2)
40 >> 2 = 00001010 (10, which is 40 / 4)
40 >> 3 = 00000101 ( 5, which is 40 / 8)
Each shift removes the rightmost bit and moves all bits one position to the right. For positive numbers, the vacated high bit is filled with 0.
Arithmetic vs. Logical Right Shift
>>(arithmetic): Fills the vacated high bits with the sign bit. Negative numbers remain negative.>>>(logical, unsigned): Always fills with 0. Negative numbers become large positive numbers.
-8 (signed 8-bit) = 11111000
-8 >> 1 = 11111100 (-4, sign preserved)
-8 >>> 1 (32-bit) = 01111...1100 (2147483644)
Rounding Behavior
For positive numbers, >> truncates toward zero (same as Math.floor(n/2)). For negative numbers, it truncates toward negative infinity:
-7 >> 1 = -4(not -3)Math.floor(-7 / 2) = -4(matches)Math.trunc(-7 / 2) = -3(different!)
When to Use Each
Use >> when working with signed integers where you want to preserve the sign. Use >>> when treating the value as unsigned (e.g., hash functions, color channels).
Use Case
Audio processing engineers use right shifts for fast volume attenuation in real-time DSP code. Reducing volume by 6 dB is approximately halving the amplitude, which can be done with a single right shift. For 16-bit audio samples, `sample >> 1` halves the volume with zero latency and no floating-point overhead, critical for real-time processing on constrained hardware.