Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned 32 bit integers in Javascript

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.

like image 888
user1367401 Avatar asked Jul 28 '12 18:07

user1367401


People also ask

What is 32-bit integer in JavaScript?

32-bit integer has range from -2147483648 ( -2^31 ) to 2147483647 ( 2^31 − 1 )

What is 32-bit unsigned integer?

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. The most significant byte is 0 and the least significant is 3.

Does JavaScript have unsigned int?

There is no built-in unsigned integer type in Javascript.

What is unsigned integer JavaScript?

The unsigned int type represents a 32-bit unsigned two's-complement integer. Integer types that are unsigned consist only of positive integers.


1 Answers

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.

like image 169
ephemient Avatar answered Sep 23 '22 13:09

ephemient