How to emulate unsigned x86 32-bit integer multiplication using JavaScript?

Compiling this code with Emscripten:

#include <stdio.h> int main() { unsigned long d1 = 0x847c9b5d; unsigned long q = 0x549530e1; printf("%lu\n", d1*q); return 0; } 

gives (using -g ):

  $d1=-2072208547; //@line 3 "minusmul.c" $q=1419063521; //@line 4 "minusmul.c" var $2=$d1; //@line 5 "minusmul.c" var $3=$q; //@line 5 "minusmul.c" var $4=((($2)*($3))|0); //@line 5 "minusmul.c" 

By doing this with js (believe in SpiderMonkey?) Or node , I get the result 3217488896 . By executing my own executable (compiled using GCC), I get 3217489085 . How can I emulate unsigned x86 32-bit integer multiplication using JavaScript?

+4
source share
2 answers

Emscripten either does not support exact 32-bit multiplication, or it is an error. Since the main page mentions that they have emulation software for 64-bit math, I think this is a mistake. I found that you can use CHECK_OVERFLOWS and it will detect overflow. It seems that he is “not repairing” it. To terminate the program using CHECK_OVERFLOWS, you need to increase the counter marked "XXX" in the generated source.

+1
source

Javascript uses the IEEE-754 standard ( see also ) as an internal numeric representation. This is floating point arithmetic, so you will have to come up with your own library functions to emulate bitwise arithmetic for large integers. There are several libraries, such as BigInt and BigNumber .

+1
source

All Articles