The meaning of Bit-wise NOT in Python [duplicate]

限于喜欢 提交于 2019-12-10 15:53:51

问题


Why bitwise not does not act as expected for toggling bits? See for example below:

a = 5
print(bin(a))
b = ~a
print(bin(b))

This is the output:

0b101
-0b110

The question is why the first bit from the left is not toggled?

Considering that Python documentation says:

~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1.


Edit: Are you saying that "~" is not the operator for simple toggling of bits, but instead it is the operator for twos complement? If so, why the sentence quoted from documentation does not tell that. The sentence above from Python documentation does not imply this to me.


回答1:


It is toggling all the bits. All of them, including an infinite number of leading zeros, producing an infinite number of leading ones:

0b...111111111111111111111111111111111111111111111111111010

because Python simulates an infinite-bit representation, not 3-bit or 32-bit or 64-bit or any finite number.

Python can't show you an infinite number of leading ones, so instead, it shows you bin(abs(b)) with a - sign in front. abs(b) is 6 and bin(6) is '0b110', so you see

-0b110


来源:https://stackoverflow.com/questions/46573219/the-meaning-of-bit-wise-not-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!