Unsigned 32 bit integers in Javascript

Viewed 8244

How can I emulate 32bit unsiged integers without any external dependencies in Javascript? Tricks with x >>> 0 or x | 0 don't work (for multiplication, they seem to work for addition / subtraction), and doubles lose precision during multiplication.

For example, try to multiply 2654435769 * 340573321 (mod 2^32). The result should be 1.

This answer has multiplication. What about addition / subtraction / division?

Here's a link to wolfram alpha, presenting the equation above.

2 Answers

You can ape it with BigInts in 2020.

const u32mul = (x, y) => Number((BigInt(x) * BigInt(y)) & 0xFFFFFFFFn);

A sufficiently smart compiler should work this out, but I haven't benchmarked this, so proceed with caution.

The other alternative would of course drop into WebAssembly. If you need to be working at this level, I'd strongly advise it.

Related