Signed vs unsigned Shift operators

In JavaScript, >> and >>> are both right-shift operators, but they behave very differently with negative numbers.


1️⃣

>>

Arithmetic right shift

👉 Preserves the sign bit

a >> b

Example

5 >> 1
// 5  = 00000000000000000000000000000101
// →  00000000000000000000000000000010
// = 2
-5 >> 1
// -5 = 11111111111111111111111111111011
// →   11111111111111111111111111111101
// = -3

✔ Keeps the number negative


2️⃣

>>>

Logical right shift

👉 Does NOT preserve the sign

a >>> b

Example

-5 >>> 1
// -5  = 11111111111111111111111111111011
// →     01111111111111111111111111111101
// = 2147483645

🚨 This is often surprising to people.


3️⃣ Key difference summary

Operator Name Sign preserved? Negative numbers
>> Arithmetic shift ✅ Yes Stays negative
>>> Logical shift ❌ No Becomes large positive

4️⃣ Why

>>

is used in Counting Bits DP

dp[i] = dp[i >> 1] + (i & 1);

❌ Using >>> here gives no benefit and can confuse readers.


5️⃣ Interview-ready one-liner ✅

>> preserves the sign bit (arithmetic shift), while >>> fills with zeros and treats the number as unsigned.


6️⃣ Rule of thumb

If you want, I can also explain:

Just say 👍