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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With