python中的“^”是做什么的

时间:2013-09-04 21:32:14

标签: python

我很难找到关于^在python中做什么的文档。

EX。

  
    
      

6 ^ 1 =       7

             

6 ^ 2 =       4

             

6 ^ 3 =       5

             

6 ^ 4 =       2

             

6 ^ 5 =       3

             

6 ^ 6 =       0

    
  

帮助?

2 个答案:

答案 0 :(得分:7)

这是bitwise exclusive-or operator,通常称为“xor”。对于操作数中的每对相应位,如果操作数位相同,则结果中的相应位为0,如果它们不同则为1。

考虑6^4

  6 = 0b0110
  4 = 0b0100
6^4 = 0b0010 = 2

正如您所看到的那样,两个数字中最低有效位(右侧,“一个”位置)为零。因此,答案中最不重要的位为零。下一位在第一个操作数中为1,在第二个操作数中为0,因此结果为1

XOR有一些有趣的属性:

a^b == b^a  # xor is commutative
a^(b^c) == (a^b)^c   # xor is associative
(a^b)^b == a  # xor is reversible
0^a == a   # 0 is the identity value
a^a == 0   # xor yourself and you go away.

您可以使用xor:

更改值的奇怪度
prev_even = odd ^ 1 (2 = 3 ^ 1)
next_odd = even ^ 1 (3 = 2 ^ 1)

答案 1 :(得分:1)

按位异或。有关更多信息,请参阅Python文档...

http://docs.python.org/2/library/operator.html

相关问题