为什么<< 32不是在javascript中导致0? [英] Why does << 32 not result in 0 in javascript?
问题描述
这是错误的:
(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:
- 让 lref 成为评估 ShiftExpression 的结果.
- 让 lval 为GetValue( lref ).
- 让 rref 成为评估 AdditiveExpression 的结果.
- 让 rval 为GetValue( rref ).
- 让 lnum 为ToInt32( lval ).
- 让 rnum 为ToUint32( rval ).
- 让* shiftCount是屏蔽掉除>的最低有效5位以外的所有位的结果. rnum ,即计算 rnum & 0x1F.
- 将 lnum 左移 shiftCount 位的结果返回.结果是一个有符号的32位整数.
- Let lref be the result of evaluating ShiftExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating AdditiveExpression.
- Let rval be GetValue(rref).
- Let lnum be ToInt32(lval).
- Let rnum be ToUint32(rval).
- Let *shiftCount be the result of masking out all but the least significant 5 bits of > rnum, that is, compute rnum & 0x1F.
- 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...
这篇关于为什么<< 32不是在javascript中导致0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!