哈克将javascript编号转换为UInt32 [英] Hack to convert javascript number to UInt32

查看:166
本文介绍了哈克将javascript编号转换为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 评估如下:


  1. lref 是评估 ShiftExpression 的结果。

  2. lval GetValue(lref)

  3. rref 成为评估<$ c $的结果c> AdditiveExpression 。

  4. rval GetValue(rref)

  5. lnum ToUint32(lval)

  6. rnum ToUint32(rval)

  7. shiftCount 成为屏蔽 rnum中除最不重要的5位之外的所有内容的结果,即计算 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 ToUint32(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 performing a zero-filling right shift of lnum by shiftCount bits. Vacated bits are filled with zero. The result is an unsigned 32-bit integer.


这篇关于哈克将javascript编号转换为UInt32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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