位运算符〜ISN&quot's'toppers“在Python。这是为什么?
我期望 bin(〜0b111000)返回值 0b000111 ,因为对我的理解,不操作将返回相反的位作为输出。
我一直在阅读“ 〜x :返回x的补充 - 您通过切换每个1的数字,而每个1的数字为1”,以便我不完全知道我的逻辑中断的位置向下。
为什么它显示 - (x + 1)而不是实际上是翻转所有位?
I'd expect bin(~0b111000) to return the value 0b000111 because to my understanding the NOT operation would return the opposite bit as output.
I keep reading that "~x: Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1" so I don't exactly know where my logic breaks down.
Why does it show -(x + 1) instead of just literally flipping all bits?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它是翻转所有位!
您似乎将
0b111000
视为6位值。事实并非如此。 Python3中的所有整数都具有(至少从概念上)无限的许多位。因此,想象0B111000
是0b [...] 00000111000
的速记。现在,翻转所有位会导致
0b [...] 11111000111
。请注意,在这种情况下,[...]代表无限的许多 ,因此从数学上讲这会变得有趣。而且我们根本无法无限地打印很多东西,因此无法直接打印此数字。但是,由于这是2s的补充,所以这仅意味着:如果我们向其添加
0b111001
的数字,将变为0
。这就是为什么您看到-0B111001
。It is flipping all the bits!
You seem to think of
0b111000
as a 6bit value. That is not the case. All integers in python3 have (at least conceptually) infinitely many bits. So imagine0b111000
to be shorthand for0b[...]00000111000
.Now, flipping all the bits results in
0b[...]11111000111
. Notice how in this case the [...] stands for infinitely many ones, so mathematically this gets interesting. And we simply cannot print infinitely many ones, so there is no way to directly print this number.However, since this is 2s complement, this simply means: The number which, if we add
0b111001
to it, becomes0
. And that is why you see-0b111001
.