0

First some background:

We know that JavaScript numbers are 64-bit values, but not all of those 64 bits are available to represent whole numbers. Hence JavaScript can NOT represent all of the 2^64 numbers.

It can, though, represent all the 2^52 whole numbers.

So the simple question is: is it absolutely not possible to do 64-bit binary to decimal conversions? Or are there some hacks.

Also, this is a bit perplexing, as I don't understand what's going on...

>>> str_64_1s = '1111111111111111111111111111111111111111111111111111111111111111';
>>> d = parseInt(str_64_1s, 2)
18446744073709552000
>>> d.toString(2)
"10000000000000000000000000000000000000000000000000000000000000000"   // 1 one + 64 zeros
>>> parseInt(d.toString(2), 2)
18446744073709552000
>>> parseInt(d.toString(2), 2) === d
true
Math.pow(2, 64) == d
true

Some related discussions:

Community
  • 1
  • 1
treecoder
  • 43,129
  • 22
  • 67
  • 91
  • It’s not possible to *easily* do *precise* conversions while keeping an actual JavaScript *integer*. Are you just looking for base conversion from one string to another? – Ry- Oct 01 '13 at 17:42
  • No, I am looking to do some serious arithmetic (additions and subtraction) on 64-bit binary numbers for my application – treecoder Oct 01 '13 at 17:43
  • 1
    The usual way to do that is to use two 32-bit integers. – Ry- Oct 01 '13 at 17:44
  • How do I use 32 bit integers for 64 bit binary numbers? – treecoder Oct 01 '13 at 17:45
  • `var high = 16; var low = -1 >>> 0; var add = 22; var newLow = low + add >>> 0; if(newLow < low) high++; low = newLow;`. That’s addition. – Ry- Oct 01 '13 at 17:48
  • Well this is a solution, but I need to do hundreds of such calculations as part of an event, and I don't have more than a few milliseconds for that. So I'd better find a faster solution. – treecoder Oct 01 '13 at 17:51
  • You need to do *hundreds* of those calculations, huh? Run this for me: `var start = Date.now(), iterations = 0, end; while(true) { end = Date.now(); if(end - start >= 1000) break; var high = 16; var low = -1 >>> 0; var add = 22; var newLow = low + add >>> 0; if(newLow < low) high++; low = newLow; iterations++; } console.log(iterations / (end - start) + " operations per millisecond");` – Ry- Oct 01 '13 at 17:55
  • (And if you run the same benchmark with an empty loop, you get about twice as many op/ms. Math is fast.) – Ry- Oct 01 '13 at 17:56
  • Alright, I'll try and see if this works for my case. Thanks. – treecoder Oct 01 '13 at 19:56

0 Answers0