4

Compiling this code using Emscripten:

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

yields (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"

Executing this using js (SpiderMonkey I believe?) or node, I get the result 3217488896. Executing the native executable (compiled using GCC), I get 3217489085. How would one emulate the x86 unsigned 32-bit integer multiplication using JavaScript?

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
  • 1
    Duplicate of http://stackoverflow.com/questions/6232939/is-there-a-way-to-correctly-multiply-two-32-bit-integers-in-javascript/6422061 – Waleed Khan Aug 23 '12 at 23:46
  • I posted an answer on the [duplicate question](http://stackoverflow.com/questions/6232939/is-there-a-way-to-correctly-multiply-two-32-bit-integers-in-javascript/6422061). – Janus Troelsen Aug 24 '12 at 04:21

2 Answers2

1

Javascript uses the IEEE-754 standard (see also) as its internal number representation. This is floating-point arithmetic, so you're going to have to come up with your own library functions to emulate bitwise arithmetic for large integers. Several libraries exist, such as BigInt and BigNumber.

Jim H.
  • 5,539
  • 1
  • 24
  • 23
  • Single precision floats can represent all numbers between 0 and 2^32-1 AFAIK, so I don't see what I need BigInts for. – Janus Troelsen Aug 23 '12 at 23:44
  • 1
    There are a lot of discussions on this topic. See http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t – Jim H. Aug 23 '12 at 23:47
1

Emscripten either does not support exact 32-bit multiplication or it is a bug. Since they mention on the homepage that they have software emulation for 64-bit math, I think it's a bug. I discovered that you can use CHECK_OVERFLOWS and it will discover the overflow. It doesn't seem to "repair" it though. To make the program finish with CHECK_OVERFLOWS you need to up the count, marked by "XXX" in the generated source.

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
  • ok turns out it was a bug. [fix here](https://github.com/kripken/emscripten/commit/c14a675125a6d94d80561e986549280eee5e958d), [issue here](https://github.com/kripken/gmp.js/issues/2) – Janus Troelsen Aug 27 '12 at 01:54