pap*_*iro 11 javascript binary bit-manipulation bitwise-operators
注意:应从右到左阅读以下所有二进制表示.我不确定为什么我这样想他们,但我实际上并不知道人们也从左到右代表二元.混乱!
在MDN关于JavaScript的按位运算符(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT)的文章中,它表示~运算符是按位运算NOT符.
在维基百科(https://en.wikipedia.org/wiki/Bitwise_operation#NOT)上,它表示"按位NOT或补码,是一个对每个位执行逻辑否定的一元运算,形成给定二进制的'补码' 0的位变为1,1的位变为0.
现在,取二进制数字5: 0101
如果我输入~5我的浏览器控制台,我会得到-6其二进制表示形式1110.我期望否定0101变成1010,实际上是10(如果最左边的数字被视为符号,则为-2).
我读到的JavaScript ~运算符的所有解释都说它将数字计算为 - (x + 1),但这并不能从逻辑上向我解释该运算符在"按位"级别上的作用.
基本上,0101成为1110.
目睹这种转变的中间步骤是什么?我看到前导位被翻转,从而改变了标志.但这就是我能收集的全部内容.
It does indeed perform a bit-wise NOT, the negative number is in two's complement. So the value 1010 is -6.
Two's complement basically works by the very left-most bit signifies a negative number and is taken as a negative value. All other 1 bits are added to this number. For example:
1010 => (-8 +0 +2 +0) => -6
1111 => (-8 +4 +2 +1) => -1
Run Code Online (Sandbox Code Playgroud)