Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hack to convert javascript number to UInt32

Edit: 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.


Question:

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:

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

So shouldn't length receive the standard 64-bit float value? Or can someone point out to me where the hack starts?

like image 342
dot slash hack Avatar asked Mar 11 '14 20:03

dot slash hack


People also ask

How do you convert a number to a string in JavaScript?

The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. The toString() method is used with a number num as shown in the above syntax using the '. ' operator.

How do I convert a string to a number in node?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.


1 Answers

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 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.

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

  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.
like image 88
filmor Avatar answered Oct 08 '22 19:10

filmor