admin管理员组

文章数量:1313743

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.

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.

Share Improve this question edited May 23, 2017 at 10:26 CommunityBot 11 silver badge asked Jul 28, 2012 at 18:28 user1367401user1367401 1,0501 gold badge17 silver badges26 bronze badges 5
  • But the result of 2654435769 * 340573321 does not fit in 32-bits... – Šime Vidas Commented Jul 28, 2012 at 18:42
  • @Šime Vidas: But mod 2^32 it does; that's what he's after with the putations if I'm understanding it correctly. – pimvdb Commented Jul 28, 2012 at 18:43
  • @pimvdb: yes, that's how 32bit unsigned integers work -- all operations are performed modulo 2^32. – user1367401 Commented Jul 28, 2012 at 18:45
  • I see. I'm surprised that doubles lose precision like this, I had no idea. – Šime Vidas Commented Jul 28, 2012 at 18:49
  • that might be helpful stackoverflow./questions/307179/… – lord.didger Commented Jul 28, 2012 at 19:14
Add a ment  | 

2 Answers 2

Reset to default 3

A 32-bit unsigned int fits within Javascript's 64-bit float -- there should be no loss of precision when performing addition, subtraction, or division. Just mask with 0xffffffff to stay within a 32-bit integer. Multiplication goes beyond what fits, but you already have a solution for that.

You can ape it with BigInts in 2020.

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

A sufficiently smart piler 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.

本文标签: Unsigned 32 bit integers in JavascriptStack Overflow