Vic
Vic

Reputation: 935

32-bit signed integer math in JavaScript

I am converting some legacy Pascal to JavaScript. I need to multiple two 32-bit signed integers.

In the following sample loop some multiplications will cause overflow and will give negative numbers. This is intentional. I need to reproduce the same final number x at the end that matches the legacy system.

How can I do this in JavaScript to achieve the same result?

Here is some sample code:

var x = new Number(some value);  // I need this to be a 32-bit signed integer
var y = new Number(some value); // I need this to be a 32-bit signed integer

for (var i=0; i<100; i++) {   
    x = x * y; 
} 
return x;

Upvotes: 8

Views: 6656

Answers (2)

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25595

Javascript's bitwise operators actually convert the value to a regular integer. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators This fact is used by things like asm.js to coerce the types, and you can do it yourself too. The trick is to put a |0 at the end of a number to force it to be 32 bit

function test() {
    var x = 255|0; // |0 does the type coercion
    var y = 255|0; // not strictly necessary at this var decl but used for explicitness

    for (var i=0; i<5; i++) {   
         x = (y * x)|0; // parens needed because |'s precedence
   } 

   return x;
}

I ran that with a few numbers and got the same result as C in Firefox.. didn't get a chance to test in IE, but I'm pretty sure this behavior is in the ECMAscript spec, so it should work.

Upvotes: 10

Pointy
Pointy

Reputation: 413709

Math operations in JavaScript are always done as double-precision floating point. You'd have to write your own multiplication routine (or find one somewhere) to carry out integer math, and that'd be slow or hard (or both :).

Upvotes: 1

Related Questions