Why is JavaScript broken or weird?

In JavaScript it seems:

(4294958077 | 0) == -9219 

Why is this not 4294958077?

This suggests that there is something like an overflow (although, as I understand it, the range of types of JavaScript numbers is +/- 9007199254740992, so it is odd on its own.)

Even if it was an overflow, of course

 (4294958077 | 0) == 4294958077 

should be evaluated as true, but it is not.

help me please

+6
source share
3 answers

This has nothing to do with the floating point type or overflows. It returns -9219 because the standard requires it, since all binary bitwise operations must be performed using signed 32-bit integers (ECMA-262 & sect; 11.10).

The product A: A @B, where @ is one of the bitwise operators in the above products, is estimated as follows:

  • Let lref be the result of A.
  • Let lval be GetValue (lref).
  • Let rref be the result of B.
  • Let rval be GetValue (rref).
  • Let lnum be ToInt32 (lval).
  • Let rnum be ToInt32 (rval).
  • Return the result of applying the bitwise operator @ to lnum and rnum. The result is a 32-bit integer.

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

+5
source

All numbers in Javascript are 64-bit floating point numbers. Bitwise operations with floats are the edge, so internally these floats are temporarily converted to a 32-bit int, then a bitwise operation is performed - therefore, your overflow.

+2
source

JavaScript bit numbers are stored as signed 64-bit floats, i.e. you only use 32 bits for an integer that you have exceeded, so it became weird by turning it into an integer as much as possible, and then operations.

More information here (especially the section β€œbeyond 32-bit”), but there is no real solution, unfortunately, you will need to work around it.

0
source

Source: https://habr.com/ru/post/908710/


All Articles