理解JavaScript按位NOT运算符和toString()函数 [英] Understanding JavaScript bitwise NOT operator and toString() function
问题描述
提前感谢所有人 -
Thanks to everyone in advance -
alert((~1).toString(2));
输出: -10
但在PHP / Java中输出11111111111111111111111111111110
But in PHP/Java it outputs 11111111111111111111111111111110
我错过了什么,为什么Javascript在输出中添加 - ?
Am I missing something, why does Javascript add a "-" to the output?
Thx,
Sam
Thx, Sam
推荐答案
我知道Java使用二进制补码表示负数,而 11111111111111111111111111111110 表示二进制,这是 ~1 给出的,表示-2。或者,以二进制形式表示带负号,-10,这就是你得到的。
I know Java uses two's complement to represent negative numbers, and 11111111111111111111111111111110 in binary, which is what ~1 gives, represents -2. Or, represented in binary with a negative sign, -10, which is what you got.
使用二进制补码计算负数10(在基数2中)的方式是你先颠倒所有的位,给你:
The way you calculate the negative of 10 (in base 2) using two's complement is that you first invert all of the bits, giving you:
11111111111111111111111111111101
然后你加1,给你:
11111111111111111111111111111110
我猜同样的事情发生在Javascript。
I guess the same is happening in Javascript.
这篇关于理解JavaScript按位NOT运算符和toString()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!