JavaScript 32-bit math standard signature

I am converting some old Pascal to JavaScript. I need some two 32-bit integers.

In the following loop example, 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 old system.

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

Here is a 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; 
+7
javascript
source share
2 answers

Javascript 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 enforce types, and you can do it yourself too. The trick is to put 0 at the end of the number to make it be 32 bits

 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 | precedence } return x; } 

I ran this with multiple numbers and got the same result as C in Firefox. I did not have the opportunity to test IE, but I am sure that this behavior is in the ECMAscript specification, so it should work.

+10
source share

Mathematical operations in JavaScript are always performed as a double point with double precision. You will need to write your own multiplication procedure (or find somewhere) to do integer math, and it will be slow or hard (or both :).

+1
source share

All Articles