You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询JavaScript中Signed right shift(>>)与Zero fill right shift(>>>)运算符的差异

Understanding the Difference Between >> (Signed Right Shift) and >>> (Zero-Fill Right Shift)

Great question! The reason your test with positive 5 gave identical results is that both operators behave the same way when working with non-negative numbers. Their key differences only become obvious when you work with negative values—let’s break this down clearly:

Core Behavior Recap

First, a quick reminder of how each operator works:

  • Signed Right Shift (>>): Shifts bits to the right, and fills the leftmost position with the original sign bit (0 for positive, 1 for negative). This preserves the number’s sign.
  • Zero-Fill Right Shift (>>>): Shifts bits to the right, and always fills the leftmost position with 0—regardless of the original sign. This treats the number as an unsigned value.

Example with Positive Numbers (Why They’re the Same)

For positive numbers like 5 (binary 0101 in 4 bits, or 000...0101 in 32 bits):

  • 5 >> 1: Shifts right 1, fills left with 0 → 0010 (decimal 2)
  • 5 >>> 1: Shifts right 1, fills left with 0 → 0010 (decimal 2)

Since the sign bit is 0, filling with the sign bit is the same as filling with 0—so results match.

Example with Negative Numbers (Where They Diverge)

Let’s use -5 to see the difference. In 32-bit binary, -5 is represented as 11111111 11111111 11111111 11111011 (two’s complement):

  • -5 >> 1: Shifts right 1, fills left with the sign bit (1) → 11111111 11111111 11111111 11111101, which is -3 in decimal. The sign is preserved, and the result is still negative.
  • -5 >>> 1: Shifts right 1, fills left with 0 → 01111111 11111111 11111111 11111101, which is 2147483645 in decimal. This converts the negative number to a large positive unsigned value.

Code Demo

// Positive numbers - same result
console.log(5 >> 1);   // Output: 2
console.log(5 >>> 1);  // Output: 2

// Negative numbers - different results
console.log(-5 >> 1);  // Output: -3
console.log(-5 >>> 1); // Output: 2147483645

Key Takeaway

  • Use >> when you want to preserve the sign of a number during right shift (e.g., dividing a negative integer by 2 and keeping it negative).
  • Use >>> when you want to treat the number as unsigned, or when you need to shift bits without preserving sign (common in low-level bit manipulation).

内容的提问来源于stack exchange,提问作者Astha Jindal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:22:14