Negative numbers to binary string in JavaScript(JavaScript中二进制字符串的负数)
问题描述
任何人都知道为什么 javascript Number.toString
函数不能正确表示负数?
Anyone knows why javascript Number.toString
function does not represents negative numbers correctly?
//If you try
(-3).toString(2); //shows "-11"
// but if you fake a bit shift operation it works as expected
(-3 >>> 0).toString(2); // print "11111111111111111111111111111101"
我真的很好奇为什么它不能正常工作或者它以这种方式工作的原因是什么?我已经搜索了它,但没有找到任何有用的东西.
I am really curious why it doesn't work properly or what is the reason it works this way? I've searched it but didn't find anything that helps.
推荐答案
简答:
toString()
函数接受小数,将其转换到二进制并添加一个-"号.
The
toString()
function takes the decimal, converts it to binary and adds a "-" sign.
零填充右移将其操作数转换为有符号 32 位两个补码格式的整数.
A zero fill right shift converts it's operands to signed 32-bit integers in two complements format.
更详细的回答:
问题 1:
//If you try
(-3).toString(2); //show "-11"
在函数 .toString()
.当你通过 .toString()
输出一个数字时:
It's in the function .toString()
. When you output a number via .toString()
:
语法
numObj.toString([radix])
numObj.toString([radix])
如果 numObj 为负,则保留符号. 就是这种情况即使基数是 2;返回的字符串是正二进制numObj 的表示前面有一个 - 符号,而不是两个符号numObj 的补码.
If the numObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the numObj preceded by a - sign, not the two's complement of the numObj.
它采用十进制,将其转换为二进制并添加-"号.
It takes the decimal, converts it to binary and adds a "-" sign.
- 以 10 为底的3"转换为以 2 为底的为11"
- 添加一个符号给我们-11"
问题 2:
// but if you fake a bit shift operation it works as expected
(-3 >>> 0).toString(2); // print "11111111111111111111111111111101"
零填充右移将其操作数转换为 带符号的 32 位整数.该操作的结果总是一个无符号的 32 位整数.
A zero fill right shift converts it's operands to signed 32-bit integers. The result of that operation is always an unsigned 32-bit integer.
所有位运算符的操作数都转换为有符号的 32 位二进制补码格式的整数.
The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.
这篇关于JavaScript中二进制字符串的负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript中二进制字符串的负数


- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06