-->

JavaScript - Bitwise Operations Part 5: Right Shift (>>) and Zero-Fill Right Shift (>>>)

How Right Shift (>>) Works

Right shifting moves bits right, keeping the sign (negative stays negative).

Example 7: Right Shift Operation

console.log(-5 >> 1); // Output: -3

Binary representation:

-5  =  11111111111111111111111111111011

>> 1 =  11111111111111111111111111111101  (-3 in decimal)

Right shift divides by 2 while keeping negative numbers negative.

How Zero-Fill Right Shift (>>>) Works

Zero-fill right shift does not preserve the sign, making it always positive.

Example 8: Zero-Fill Right Shift

console.log(-5 >>> 1); // Output: 2147483645

Explanation:

>>> fills with 0s, so negative numbers become large positives.

Used for unsigned integer calculations.