python xor行为与正/负数混合

发布于 2025-02-06 15:50:36 字数 221 浏览 2 评论 0原文

这是我xor 2整数时得到的两个结果。 Sames位,但XOR的第二个参数的符号不同。

>>> bin(0b0001 ^ -0b0010)
'-0b1'
>>> bin(0b0001 ^  0b0010)
'0b11'

我真的不理解逻辑。 Xor不是只是一一认为Xor吗?即使有签名的位?我希望获得相同的结果(带有不同的标志)。

Here is two results I get when I xor 2 integers. The sames bits, but a different sign for the second parameter of the xor.

>>> bin(0b0001 ^ -0b0010)
'-0b1'
>>> bin(0b0001 ^  0b0010)
'0b11'

I don't really understand the logic. Isn't XOR just supposed so XOR every bit one by one ? Even with signed bits ? I would expect to get the same results (with a different sign).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

余生再见 2025-02-13 15:50:36

如果Python的整数是固定宽度(例如:32位或64位),则以2的补体形式表示负数。也就是说,如果您想要-A,请取a的位,将它们全部倒置,然后添加1。然后a ^ b仅仅是ab在两者补充中的位xor表示的数字。结果在两者的补充中重新解释(即设置了顶部位,即负)。

python的int类型不是固定宽度,但是a ^ b的结果遵循相同的模式:想象一下值表示为广泛的固定固定在int类型,然后取两个值的XOR。

尽管现在似乎有些任意,但从历史上讲是有意义的:python通过C采用了许多操作,因此Xor被定义为C. Python中的工作方式,例如C等固定宽度整数类型,并且具有a ^ b < /code>给出相同的结果,以实质上迫使当前定义固定宽度和arbital宽度整数类型。

返回一个有效的示例:1 ^ -2。 8位足以表示这两个值。在2的补充中:

 1 = 00000001
-2 = 11111110

然后,位XOR是:

   = 11111111

这是-1的8位2的补充表示形式。尽管我们在这里使用了8个位,但是无论选择的宽度足以代表两个值,结果都是相同的。

If python's integers were fixed-width (eg: 32-bit, or 64-bit), a negative number would be represented in 2's complement form. That is, if you want -a, then take the bits of a, invert them all, and then add 1. Then a ^ b is just the number that's represented by the bitwise xor of the bits of a and b in two's complement. The result is re-interpreted in two's complement (ie: negative if the top bit is set).

Python's int type isn't fixed-width, but the result of a ^ b follows the same pattern: imagine that the values are represented as a wide-enough fixed-with int type, and then take the xor of the two values.

Although this now seems a bit arbitrary, it makes sense historically: Python adopted many operations from C, so xor was defined to work like in C. Python had a fixed-width integer type like C, and having a ^ b give the same result for the fixed-width and arbitary-width integer types essentially forces the current definition.

Back to a worked example: 1 ^ -2. 8 bits is more than enough to represent these two values. In 2's complement:

 1 = 00000001
-2 = 11111110

Then the bitwise xor is:

   = 11111111

This is the 8-bit 2's complement representation of -1. Although we've used 8 bits here, the result is the same no matter the width chosen as long as it's enough to represent the two values.

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