JavaScript的十进制二进制 - 64位 [英] Javascript Decimal to Binary - 64 bit
问题描述
有关小数-805306368二进制是:
The binary for the decimal -805306368 is:
11111111111111111111111111111111 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不使用二进制补码再presentation,它使用了 - 在
字符字符串的前面。这是因为它不知道你的电话号码范围内有多少位了。
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位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!