按位不,有人可以解释这个例子吗?

Bitwise not, can somebody explain this example?

谁能用二进制数字解释这个例子?

>>> ~11
-12
def toBinary(n):
    return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])

toBinary(11) Returns

0000000000000000000000000000000000000000000000000000000000001011

toBinary(-12) Returns

1111111111111111111111111111111111111111111111111111111111110100

来自 Python 文档 ~x : Returns x 的补码 - 通过将每个 1 换成 0 和每个 0 换成 1 得到的数字。这与 -x - 1 相同。 更多:https://wiki.python.org/moin/BitwiseOperators

使用 8 位表示(您可以使用更大的表示来获得相同的结果):

~11 => ~ b 00001011

应用 NOT 运算符收益率(1 变为 0,反之亦然):

~(b 00001011) => b 11110100

结果为负(因为最左边的位是符号位)。要发现其值,请应用 2 的补码运算符(请参阅 here):

b 11110100, negate bits:
b 00001011, add 1:
+        1
----------
b 00001100 => 12

意思是结果是-12。