Popular Posts

Why does Math.imul return this value?

QUESTION : 

console.log(-559038841 * 2654435761); //returns -1483932691338393000

console.log(Math.imul(-559038841 , 2654435761)); // returns 1445956183.

I expected the two to have the same - value but they do not. Why is this?

I imagine this has to do with the 32-bit nature of math.imul but not sure.


ANSWER : 


According to the spec, Math.imul not only converts its opreands to unsigned 32-bit integers before performing the multiplication, but also limits the result to a 32-bit integer by performing modulo 2^32 on the result[1]. So the end result cannot be bigger than 2^32 - 1 which equals 4294967295.

After that, it also converts it to a signed integer by treating the most significant bit as a sign bit, so the actual end result is between -(2^31) and 2^31 - 1, or between -2147483648 and 2147483647

[1] I suppose that in practice the engine simply drops the extra bits and keeps the less significant 32 bits. But the effect is the same as performing modulo 2^32.

Why does Math.imul return this value? Why does Math.imul return this value? Reviewed by Snehal Vasava on April 04, 2023 Rating: 5

No comments:

Breaking

Powered by Blogger.