>> 和有什么不一样?和>> JavaScript 中的运算符

发布于 2024-12-27 21:00:29 字数 218 浏览 4 评论 0原文

运行以下 JavaScript 代码在两种情况下都会显示 63

  alert( 0xff >> 2 );
  alert( 0xff >>> 2 );

>>>>> 之间有什么区别?他们的结果似乎是平等的。

Running the following JavaScript code shows 63 in both cases:

  alert( 0xff >> 2 );
  alert( 0xff >>> 2 );

What is the differences between >> and >>>? Their results seem to be equal.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

各空 2025-01-03 21:00:29

>> 是按位运算符,它将位向右移动。右侧的所有位都会丢失。

 8 = 1000
     ^-->1
   = 0000 = 0

>>>>> 执行类似的操作,但它是无符号的,这意味着它的范围从 0 到 232-1 而不是 +/- 231-1。

要查看第一个语句的实际结果,让我们使用按位运算符对数字进行取整:

1.234 >> 0         =  1 // Ok, fraction lost
1.234 >>>0         =  1 // Ok, fraction lost
-1.23 >> 0         = -1 // Ok, fraction lost
-1.23 >>>0         = 4294967295 // (negative numbers are not within the range)

Math.pow(2,31) >> 0  = -2147483648 // 2^31 is out of range
Math.pow(2,31) >>> 0 = 2147483648

因此,当超出范围的上限时,计算将在其下限继续进行,反之亦然(例如 <<)。下图显示了当您使用 n = (n + 1) >> 时会发生什么情况0 和 >>> 0,对于从最低边界开始的n

// Signed       Unsigned
     >>            >>>
-2147483647             0
-2147483646             1
...                   ...
 2147483646    4294967294
 2147483647    4294967295
-2147483647             0
-2147483646             1

>> is a bitwise operator, which shift the bits to the right. Any bits at the right are lost.

 8 = 1000
     ^-->1
   = 0000 = 0

>>> does the similar thing as >>, but it's unsigned, which means that it ranges from 0 to 232-1 instead of +/- 231-1.

To see the result of my first statement in action, let's use the bitwise operator to floor a number:

1.234 >> 0         =  1 // Ok, fraction lost
1.234 >>>0         =  1 // Ok, fraction lost
-1.23 >> 0         = -1 // Ok, fraction lost
-1.23 >>>0         = 4294967295 // (negative numbers are not within the range)

Math.pow(2,31) >> 0  = -2147483648 // 2^31 is out of range
Math.pow(2,31) >>> 0 = 2147483648

So, when the upper boundary of a range is exceeded, the calculation will continue at its lower range, and vice versa (eg <<). The following illustrates shows what happens when you use n = (n + 1) >> 0, and >>> 0, for n starting at the lowest boundary.

// Signed       Unsigned
     >>            >>>
-2147483647             0
-2147483646             1
...                   ...
 2147483646    4294967294
 2147483647    4294967295
-2147483647             0
-2147483646             1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文