Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of bits in Javascript numbers

Tags:

javascript

I work in Javascript with integer numbers only (mainly adding numbers and shifting them). I wonder how big they can be without loosing any bits.

For example, how big X can be such that 1 << X will represent 2^X ?

like image 850
Misha Moroshko Avatar asked May 10 '10 13:05

Misha Moroshko


People also ask

How many bits are JavaScript numbers?

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#.

How many bytes is a JavaScript number?

Number type. The Number type is a double-precision 64-bit binary format IEEE 754 value.

What is 32-bit integer in JavaScript?

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

Does JavaScript support 64-bit integers?

Since JavaScript does not natively support 64-bit integers, 64-bit Ids are instead represented as strings. Strings containing 64-bit Ids are distinguished from ordinary strings through use of the Id64String type alias.


2 Answers

All numbers in JavaScript are actually IEEE-754 compliant floating-point doubles. These have a 53-bit mantissa which should mean that any integer value with a magnitude of approximately 9 quadrillion or less -- more specifically, 9,007,199,254,740,991 -- will be represented accurately.


NOTICE: in 2018 main browsers and NodeJS are working also with the new Javascript's primitive-type, BigInt, solving the problems with integer value magnitude.

like image 79
LukeH Avatar answered Sep 20 '22 17:09

LukeH


All answers are partially wrong - Maybe due the new ES6/ES7 specs - , read why:

First of all, in JavaScript, the representation of the number is 2^53 - 1 that is true for @Luke answer, we can prove that by running Number.MAX_SAFE_INTEGER that will show a big number, then we do log2 to confirm that the number of bits is the same :

Number.MAX_SAFE_INTEGER 9007199254740991  Math.log2(9007199254740991) 53 

enter image description here

However, Bitwise operation are calculated on 32 bits ( 4 bytes ), meaning if you exceed 32bits shifts you will start loosing bits.

Welcome to Javascript!

like image 31
Marwen Trabelsi Avatar answered Sep 19 '22 17:09

Marwen Trabelsi