Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JavaScript bitwise OR behaving strangely?

In JavaScript, it seems:

(4294958077 | 0) == -9219

Why is it not 4294958077 ?

It suggests that there's some sort of overflow kicking in (although as I understand it a JavaScript Number type's range is +/- 9007199254740992 so that's odd in itself.)

Even if it was an overflow, surely

(4294958077 | 0) == 4294958077

should evaluate as true - but it doesn't.

Help please

like image 975
Peter Howe Avatar asked Feb 17 '12 14:02

Peter Howe


1 Answers

It has nothing to do with floating point type or overflows. It returns -9219 because the standard mandates it, as all binary bitwise operations have to be done using signed 32-bit integers (ECMA-262 §11.10).

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. Let rref be the result of evaluating B.
  4. Let rval be GetValue(rref).
  5. Let lnum be ToInt32(lval).
  6. Let rnum be ToInt32(rval).
  7. Return the result of applying the bitwise operator @ to lnum and rnum. The result is a signed 32 bit integer.

4294958077 converted to a signed 32-bit integer (using the algorithm in ECMA-262 §9.5) is -9219, and 0 is still 0, so the bitwise-or will return -9219.

like image 125
kennytm Avatar answered Sep 21 '22 11:09

kennytm