I'm trying to understand how JS engines convert a JS Number (Float64) to a 32-bit signed integer. I read that one can quickly convert a 64 bit float to a 32 bit signed integer with the bitwise OR like:
-8589934590 | 0 // which gives 2
I can't understand where does the 2 come from. According to the spec, the ToInt32 algorithm does this (the bold text is mine, not the spec's):
- Let number be ? ToNumber(argument): -8589934590 is already a Number
- If number is NaN, +0, -0, +∞, or -∞, return +0.: No
- Let int be the Number value that is the same sign as number and whose magnitude is floor(abs(number)): -8589934590 is already an integer
- Let int32bit be int modulo 2³² Since 2³² is positive the result should also be positive. In JS the remainder operator uses the sign of the left operand, so to get a modulo in this case (where -8589934590 is negative), we negate it:
let int32bit = 8589934590 % 2**32 // 4294967294 which has 32 bit length 0b11111111111111111111111111111110 - If int32bit ≥ 2³¹, return int32bit - 2³²; otherwise return int32bit. int32bit is smaller 2³¹ (since it's negative), so I use
int32bitwhich equals-2(Even if we consider0b11111111111111111111111111111110an unsigned integer, then it's greater 2³¹ and int32bit - 2³² still equals-2
Could someone, please, explain, do I correctly understand the ToInt32 algorithm and the bitwise OR operator?