JavaScript中的二进制字符串的负数 [英] Negative numbers to binary string in JavaScript

查看:140
本文介绍了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.

推荐答案

简答:



Short answer:


  1. toString()函数基本上取小数,转换为
    二进制并添加 - 符号。

  1. The toString() function basically takes the decimal, converts it to binary and adds a "-" sign.

零填充右移将其操作数转换为32个有符号位
整数,采用两种补码格式。

A zero fill right shift converts it's operand to a 32 signed bit integer 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.

所以基本上它需要十进制,将其转换为二进制并添加 - 符号。

So basically it takes the decimal, converts it to binary and adds a "-" sign.


  1. 转换为基数2的基数103为11

  2. 添加符号给出我们-11

问题2:

// but if you fake a bit shift operation it works as expected
        (-3 >>> 0).toString(2); // print "11111111111111111111111111111101"

零填充右移将其操作数转换为 32个有符号位整数

A zero fill right shift converts it's operand to a 32 signed bit integer.


所有位运算符的操作数都以二进制补码格式转换为带符号的32位
整数。

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.

这篇关于JavaScript中的二进制字符串的负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆