位运算符〜ISN&quot's'toppers“在Python。这是为什么?

发布于 2025-01-25 05:11:08 字数 208 浏览 3 评论 0原文

我期望 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

轻拂→两袖风尘 2025-02-01 05:11:08

翻转所有位!

您似乎将0b111000视为6位值。事实并非如此。 Python3中的所有整数都具有(至少从概念上)无限的许多位。因此,想象0B1110000b [...] 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 imagine 0b111000 to be shorthand for 0b[...]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, becomes 0. And that is why you see -0b111001.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文