0

I want to perform bitwise operations with some large values:

var someVariable = 4;
someVariable |= 36028797018963968; // add flag, 1 << 55

However, the result always ends up being 4 instead of 36028797018963972. After some research, I came across this answer which stated that Javascript converts the number to a 32-bit representation when doing bitwise operations, which explains why I might be having this problem, but how can I resolve it? After some more research, I came across some Javascript bigint libraries, but I would like to do this without libraries if possible. How can I perform bitwise operations on large numbers in Javascript?

Community
  • 1
  • 1
arao6
  • 3,316
  • 5
  • 30
  • 51
  • 4
    Even your `36028797018963968` is not really working, if you do console.log(36028797018963968), won´t show that, as its above int limit for js. Depending on the operations you need, would need to manage with strings or a big int library – juvian Oct 17 '14 at 17:52

2 Answers2

0

In chrome the variable Number.MAX_SAFE_INTEGER holds the max safe number you can use for math.

In my chrome this returns Number.MAX_SAFE_INTEGER = 9007199254740991. Your number is bigger.

Try this test:

var a = 36028797018963968;
var b = a+1;
console.log(a==b); // prints true
console.log(a===b); // prints true
console.log(a.toString(2)) // a to binary returns 2^56 which is not a

Also some info

var a = Number.MAX_SAFE_INTEGER;
a.toString(2);     // prints  "11111111111111111111111111111111111111111111111111111"
(a+1).toString(2); // prints "100000000000000000000000000000000000000000000000000000" <-- 2^56
(a+2).toString(2); // prints "100000000000000000000000000000000000000000000000000000"
GramThanos
  • 3,572
  • 1
  • 22
  • 34
0

Thank you @ThanasisGrammatopoulos and @juvian. After researching a lot of existing implementations, I came across a little gem for representing 64 bit two's-complement integers, long.js.

Using it is pretty straight-forward:

var a = Long.fromString("36028797018963968", true);
var b = Long.fromString("4", true);
alert('value is ' + a.or(b).toString()); // value is 36028797018963972
arao6
  • 3,316
  • 5
  • 30
  • 51