Javascript Decimal to Binary - 64 bit

2020-02-11 06:07发布

The binary for the decimal -805306368 is:

11111111111111111111111111111111 11010000000000000000000000000000

However, in Javascript I get the following:

   var str = parseInt(-805306368).toString(2);
   document.write(str);

-110000000000000000000000000000

Can anyone explain how to parse the 64 bit binary string from this decimal?

2条回答
叼着烟拽天下
2楼-- · 2020-02-11 06:23

You can use parseInt() again. It has an optional second parameter, that enables you to specify the radix (or base) of the number in the string you are trying to parse.

Such as: parseInt("-110000000000000000000000000000", 2) // gives -805306368

查看更多
贪生不怕死
3楼-- · 2020-02-11 06:24

JavaScript does not use the two's-complement representation, it uses a - character in front of the string. That's because it does not know how many bits your number range has.

To get the expected result, you could invert each bit:

>>> (~-805306368).toString(2)
"101111111111111111111111111111"

Yet, javascript does all binary operations on 32-bit integers, so this won't work for bigger (or smaller) numbers and at least will be very confusing. So, you would need to implement your own formatting algorithm.

// example of to 32-bit-conversion:
>>> (~parseInt("1111111111111111111111111111111",2)).toString(2)
"-10000000000000000000000000000000"
>>> (~parseInt("11111111111111111111111111111111",2)).toString(2)
"0"

My Implementation:

String.prototype.padleft = function(len, chr){...}

function get64binary(int) {
    if (int>=0)
        return int
          .toString(2)
          .padleft(64, "0");
    // else
    return (-int-1)
      .toString(2)
      .replace(/[01]/g, function(d){return +!+d;}) // hehe: inverts each char
      .padleft(64, "1");
}
查看更多
登录 后发表回答