Javascript Decimal to Binary - 64 bit(Javascript 十进制到二进制 - 64 位)
问题描述
十进制-805306368的二进制是:
The binary for the decimal -805306368 is:
1111111111111111111111111111111 11010000000000000000000000000000
11111111111111111111111111111111 11010000000000000000000000000000
但是,在 Javascript 中,我得到 以下:
However, in Javascript I get the following:
var str = parseInt(-805306368).toString(2);
document.write(str);
-110000000000000000000000000000
-110000000000000000000000000000
谁能解释一下如何解析这个十进制的 64 位二进制字符串?
Can anyone explain how to parse the 64 bit binary string from this decimal?
推荐答案
JavaScript 不使用补码表示,它在字符串前面使用 -
字符.那是因为它不知道你的数字范围有多少位.
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"
然而,javascript 对 32 位整数执行所有二进制操作,因此这不适用于更大(或更小)的数字,并且至少会非常混乱.因此,您需要实现自己的格式化算法.
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"
我的实现:
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");
}
这篇关于Javascript 十进制到二进制 - 64 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!