var result = (20000000 * 48271) % 0x7FFFFFFF;
But in some programming languages, that first
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.
To convert to a signed 32-bit integer:
x = (a * b) | 0;
To convert to an unsigned 32-bit integer:
x = (a * b) >>> 0;
Another way to achieve this is to convert to a format where you can remove extra bytes before converting back to integer. That may not be optimal for JS but can be helpful in environments with really restricted operators.
For instance with hexadecimal:
var hugeInteger = 999999999999999; var ui32 = parseInt(hugeInteger.toString(16).slice(-8), 16); // ui32 == 2764472319
It's also possible to get the overflow from
User contributions licensed under CC BY-SA 3.0