JavaScript summing large integers

Raven picture Raven · Dec 29, 2010 · Viewed 48.8k times · Source

In JavaScript I would like to create the binary hash of a large boolean array (54 elements) with the following method:

function bhash(arr) {
   for (var i = 0, L = arr.length, sum = 0; i < L; sum += Math.pow(2,i)*arr[i++]); 
   return sum;
}

In short: it creates the smallest integer to store an array of booleans in. Now my problem is that javascript apparently uses floats as default. The maximum number I have to create is 2^54-1 but once javascript reaches 2^53 it starts doing weird things:

9007199254740992+1 = 9007199254740994

Is there any way of using integers instead of floats in javascript? Or large integer summations?

Answer

martona picture martona · Dec 29, 2010

JavaScript uses floating point internally.

What is JavaScript's highest integer value that a number can go to without losing precision?

In other words you can't use more than 53 bits. In some implementations you may be limited to 31.

Try storing the bits in more than one variable, use a string, or get a bignum library, or if you only need to deal with integers, a biginteger library.