哈克将javascript编号转换为UInt32 [英] Hack to convert javascript number to UInt32
问题描述
修改:由于Polyfill示例已更新,此问题已过期。我在这里留下这个问题仅供参考。阅读关于按位移位运算符的有用信息的正确答案。
This question is out of date as the Polyfill example has been updated. I'm leaving the question here just for reference. Read the correct answer for useful information on bitwise shift operators.
问题:
Mozilla的Polyfill示例中的第7行 Array.prototype.indexOf 页面他们评论这个:
On line 7 in the Polyfill example of the Mozilla Array.prototype.indexOf page they comment this:
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
但按位移位规范明确指出运算符返回与左操作数相同类型的值:
But the bitwise shift specification on Mozilla clearly states that the operator returns a value of the same type as the left operand:
移位运算符将其操作数转换为32位整数并返回与左操作数相同类型的结果。
Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.
那么长度是否应该接收标准的64位浮点值?或者有人可以向我指出黑客入手的地方?
So shouldn't length receive the standard 64-bit float value? Or can someone point out to me where the hack starts?
推荐答案
ECMAScript规范声明该值在步骤中转换为UInt32 http://www.ecma-international.org/ecma-262/5.1的第5和第8页/#sec-11.7 :
The ECMAScript specification states that the value is converted to UInt32 in step 5 and 8 of http://www.ecma-international.org/ecma-262/5.1/#sec-11.7:
11.7.3无符号右移运算符(>>>)
对左操作数执行零填充按位右移操作,操作数由右操作数指定。
11.7.3 The Unsigned Right Shift Operator ( >>> )
Performs a zero-filling bitwise right shift operation on the left operand by the amount > specified by the right operand.
生产 ShiftExpression:ShiftExpression>>> AdditiveExpression
评估如下:
- 设
lref
是评估ShiftExpression
的结果。 - 设
lval
是GetValue(lref)
。 - 让
rref
成为评估<$ c $的结果c> AdditiveExpression 。 - 让
rval
为GetValue(rref)
。 - 设
lnum
是ToUint32(lval)
。 - 设
rnum
是ToUint32(rval)
。 - 让
shiftCount
成为屏蔽rnum中除最不重要的5位之外的所有内容的结果
,即计算rnum& 0x1F
。 - 返回
lnum
执行零填充右移的结果shiftCount
位。空位用零填充。 结果是无符号的32位整数。
- Let
lref
be the result of evaluatingShiftExpression
. - Let
lval
beGetValue(lref)
. - Let
rref
be the result of evaluatingAdditiveExpression
. - Let
rval
beGetValue(rref)
. - Let
lnum
beToUint32(lval)
. - Let
rnum
beToUint32(rval)
. - Let
shiftCount
be the result of masking out all but the least significant 5 bits ofrnum
, that is, computernum & 0x1F
. - Return the result of performing a zero-filling right shift of
lnum
byshiftCount
bits. Vacated bits are filled with zero. The result is an unsigned 32-bit integer.
这篇关于哈克将javascript编号转换为UInt32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!