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 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript 十进制到二进制 - 64 位
基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
