Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does Math.imul return this value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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. 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading