python xor行为与正/负数混合
这是我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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果Python的整数是固定宽度(例如:32位或64位),则以2的补体形式表示负数。也就是说,如果您想要
-A
,请取a
的位,将它们全部倒置,然后添加1。然后a ^ b
仅仅是a
和b
在两者补充中的位xor表示的数字。结果在两者的补充中重新解释(即设置了顶部位,即负)。python的
int
类型不是固定宽度,但是a ^ b
的结果遵循相同的模式:想象一下值表示为广泛的固定固定在int类型,然后取两个值的XOR。尽管现在似乎有些任意,但从历史上讲是有意义的:python通过C采用了许多操作,因此Xor被定义为C. Python中的工作方式,例如C等固定宽度整数类型,并且具有
a ^ b < /code>给出相同的结果,以实质上迫使当前定义固定宽度和arbital宽度整数类型。
返回一个有效的示例:
1 ^ -2
。 8位足以表示这两个值。在2的补充中:然后,位XOR是:
这是-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 ofa
, invert them all, and then add 1. Thena ^ b
is just the number that's represented by the bitwise xor of the bits ofa
andb
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 ofa ^ 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:Then the bitwise xor is:
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.