Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Simulate" a 32-bit integer overflow in JavaScript

JavaScript can handle the following Math just fine:

var result = (20000000 * 48271) % 0x7FFFFFFF;

But in some programming languages, that first int*int multiplication results in a value too large to hold in a standard 32 bit integer. Is there any way to "simulate" this in JavaScript, and see what the resulting calculation would be if the multiplication resulted in an integer overflow?

like image 882
IQAndreas Avatar asked May 10 '14 06:05

IQAndreas


2 Answers

In newer browsers, Math.imul(a,b) will give you an actual 32-bit integer multiplied result, with overflow resulting the way you would expect (it gives the lower half of the 64-bit result as what it returns).

However, as far as I know there's no way to actually get the overflow, (the upper 32 bits) but the modulus you showed in your answer gets rid of that information, so I figure that's not what you want. If they were going to do overflow, they'd have to separate it based on signed and unsigned anyway.

I know this works in Chrome, Firefox, and Opera, not sure about the rest, though pretty sure IE doesn't have it (typical). You'd need to fall back to a shim such as this one.

like image 112
TND Avatar answered Oct 25 '22 17:10

TND


It is possible to simulate 32-bit integer by "abusing" the bitwise operators available in JavaScript (since they can only return integers within that range).

To convert to a signed 32-bit integer:

x = (a * b) | 0;

To convert to an unsigned 32-bit integer:

x = (a * b) >>> 0;
like image 33
IQAndreas Avatar answered Oct 25 '22 16:10

IQAndreas