为什么<< 32不是在javascript中导致0? [英] Why does << 32 not result in 0 in javascript?

查看:77
本文介绍了为什么<< 32不是在javascript中导致0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是错误的:

(0xffffffff << 31 << 1) === (0xffffffff << 32)

似乎应该是对的.在任何地方添加>>> 0都不会改变.

It seems like it should be true. Adding >>> 0 anywhere does not change this.

这是为什么,如何正确编写处理<< 32的代码?

Why is this and how can I correctly write code that handles << 32?

推荐答案

移位运算符始终有效 的右操作数在0-31范围内.

The shift operators always effectively has a right operand in the range 0-31.

来自 Mozilla文档:

Shift运算符将其操作数按big-endian顺序转换为32位整数,并返回与左操作数相同类型的结果.正确的操作数应小于32,但是如果不仅会使用低5位,.

或者通过 ECMAscript 5标准:

生产ShiftExpression:ShiftExpression<< AdditiveExpression的评估如下:

The production ShiftExpression : ShiftExpression << AdditiveExpression is evaluated as follows:

  1. lref 成为评估 ShiftExpression 的结果.
  2. lval 为GetValue( lref ).
  3. rref 成为评估 AdditiveExpression 的结果.
  4. rval 为GetValue( rref ).
  5. lnum 为ToInt32( lval ).
  6. rnum 为ToUint32( rval ).
  7. 让* shiftCount是屏蔽掉除>的最低有效5位以外的所有位的结果. rnum ,即计算 rnum & 0x1F.
  8. lnum 左移 shiftCount 位的结果返回.结果是一个有符号的32位整数.
  1. Let lref be the result of evaluating ShiftExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating AdditiveExpression.
  4. Let rval be GetValue(rref).
  5. Let lnum be ToInt32(lval).
  6. Let rnum be ToUint32(rval).
  7. Let *shiftCount be the result of masking out all but the least significant 5 bits of > rnum, that is, compute rnum & 0x1F.
  8. Return the result of left shifting lnum by shiftCount bits. The result is a signed 32-bit integer.

(其他移位运算符也是如此.)

(And likewise for other shift operators.)

我尚不清楚为什么会这样,但是Java和C#对于其32位整数类型的工作方式相同. (对于64位整数类型,操作数的范围为0-63.)请参见

It's not entirely clear to me why this is the case, but Java and C# work the same way for their 32-bit integer types. (For 64-bit integer types, the operand is in the range 0-63.) See JLS 15.19 for example.

我的猜测是,这在常见的处理器平台上很有效,但是我没有证据表明这一点...

My guess is that this is efficient on common processor platforms, but I don't have evidence of that...

这篇关于为什么&lt;&lt; 32不是在javascript中导致0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆