4

Here I found the following piece of code:

hash = hash | 0; // Convert to 32bit integer

Could anyone explain why this code converts hash to 32 bit integer?

  • Notice that [`>>> 0`](https://stackoverflow.com/q/1822350/1048572) is more common: it ensures that the result is positive by converting to an *unsigned* 32 bit integer. – Bergi Jan 28 '19 at 17:35

2 Answers2

4

The reason is that bitwise operators implicitly convert their arguments to 32-bit ints before applying the operator. Other than that, | 0 performs a bitwise OR with 0, which is essentially a no-op.

In the ES6 spec, the | operator is defined as a binary operator in 12.11, and then the runtime semantics are defined in 12.11.3.

In particular, steps 7 and 9 cast the arguments to 32-bit ints, and step 11 returns the result as a 32-bit int:

The production A : A @ B, where @ is one of the bitwise operators in the productions above, is evaluated as follows:

  1. Let lref be the result of evaluating A.
  2. Let lval be GetValue(lref).
  3. ReturnIfAbrupt(lval).
  4. Let rref be the result of evaluating B.
  5. Let rval be GetValue(rref).
  6. ReturnIfAbrupt(rval).
  7. Let lnum be ToInt32(lval).
  8. ReturnIfAbrupt(lnum).
  9. Let rnum be ToInt32(rval).
  10. ReturnIfAbrupt(rnum).
  11. Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.

[emphasis added]

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
3

It is because | is an bitwise operator. SO

hash = hash | 0;

performs the bitwise or operation, i.e bitwise or of hash and zero.

You will observe similar behaviour for other bitwise operators too, for example :

var x = 4;

console.log(4 >> 1); // right shift bitwise operator

Thanks to @Keith to mention that" Bitwize operation in JS, are only 32bit signed int's." in comment.

amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • Thank you, I know that, suppose we have 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 and zero, in which all bits are `0`. If we do | we will get 5 bytes. –  Jan 28 '19 at 17:09
  • @Jim2018 Bitwize operation in JS, are only 32bit signed int's. – Keith Jan 28 '19 at 17:18
  • @Keith if this is true, then this is the the key point and should be added to the answer. –  Jan 28 '19 at 17:26
  • @Jim2018 Yes, indeed I think the answer would benefit from this. I'll leave this for amrender to update his answer if he wants too. – Keith Jan 28 '19 at 17:29
  • @Keith Thanks for the additional info. And please feel free to update my answer, thanks – amrender singh Jan 28 '19 at 17:48