Python ^ (XOR) 运算符有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14526584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the ^ (XOR) operator do?
提问by Hilary Park
What mathematical operation does XOR perform?
XOR 执行什么数学运算?
回答by Martijn Pieters
^isthe Python bitwise XOR operator. It is how you spell XORin python:
^是的Python的按位异或运算符。这是你XOR在python中拼写的方式:
>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0
XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:
XOR 代表异或。它用于密码学,因为它让您可以在可逆操作中使用掩码“翻转”位:
>>> 10 ^ 5
15
>>> 15 ^ 5
10
where 5is the mask; (input XOR mask) XOR maskgives you the input again.
5面具在哪里;(输入异或掩码)异或掩码再次为您提供输入。
回答by phant0m
XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly oneof the bits is set.
XOR 是一种二元运算,它代表“异或”,也就是说,如果仅设置了一位,则结果位评估为 1 。
This is its function table:
这是它的功能表:
a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
This operation is performed between every two corresponding bits of a number.
该操作在一个数的每两个对应位之间执行。
Example: 7 ^ 10
In binary: 0111 ^ 1010
示例:7 ^ 10
在二进制中:0111 ^ 1010
0111
^ 1010
======
1101 = 13
Properties:The operation is commutative, associative and self-inverse.
性质:该操作是可交换的、结合的和自逆的。
It is also the same as addition modulo 2.
它也与加法模 2 相同。
回答by nagendra547
A little more information on XOR operation.
关于异或运算的更多信息。
- XOR a number with itself odd number of times the result is number itself.
- XOR a number even number of times with itself, the result is 0.
- Also XOR with 0 is always the number itself.
- XOR 一个数字与它本身的奇数次结果是数字本身。
- 与自身异或偶数次,结果为 0。
- 此外,与 0 的 XOR 始终是数字本身。

