Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a JavaScript binary string and back again is not equal

I have a 64 element JavaScript array that I'm using as a bitmask. Unfortunately, I've run into a problem when converting from a string to binary, and back. This has worked for some other arrays, but what is going on here?

var a = [1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 0, 0, 1, 1, 1, 1,
         1, 1, 0, 0, 1, 1, 1, 1,
         1, 1, 0, 0, 0, 0, 1, 1,
         1, 1, 0, 0, 0, 0, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1, 1];

var str1 = a.join('');
  //-> '1111111111111111110011111100111111000011110000111111111111111111'

var str2 = parseInt(str1, 2).toString(2);
  //-> '1111111111111111110011111100111111000011110001000000000000000000'

str1 === str2  //-> false

I would expect str2 to be the same as str1, which is not the case.

like image 632
Marcus Booster Avatar asked May 17 '26 15:05

Marcus Booster


1 Answers

In JavaScript, the Number type is a 64-bit double-precision value (more, and more). You've specified 64 bits there, which is beyond the realm that a 64-bit double-precision value can specify accurately (as it's a floating point type, and so must devote some bits to precision). JavaScript doesn't have an integer type (much less a 64-bit version of one), which is what a perfect-fidelity conversion would require.

I'm not all that up on floating point bit representations, but IIRC a 64-bit double-precision number can accurately represent integer values on the order of 53 significant bits, see the links for details.

like image 61
T.J. Crowder Avatar answered May 20 '26 04:05

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!