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;
the max 32-bit integer I believe is (2^31) which is 2,147,483,647. This is so that negative values can be stored as well (-2^31) being the 32 bit limit (this is what "signed" means). So any number higher than that, you can return 0 for the sake of your program.
A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.
Since JavaScript does not natively support 64-bit integers, 64-bit Ids are instead represented as strings. Strings containing 64-bit Ids are distinguished from ordinary strings through use of the Id64String type alias.
A 32-bit integer limit allows for 4,294,967,296 (232 2 3 2 ) pieces of data. If storing signed integers, this would range from -2,147,483,648 to 2,147,483,647.
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.
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 :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With