views:

512

answers:

3

I ran across the caret operator in python today and trying it out, I got the following output:

>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>>> 8^0
8
>>> 7^1
6
>>> 7^2
5
>>> 7^7
0
>>> 7^8
15
>>> 9^1
8
>>> 16^1
17
>>> 15^1
14
>>>

It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find much about this searching sites other than it behaves oddly for floats, does anybody have a link to what this operator does or can you explain it here?

+10  A: 

It's a bit-by-bit exclusive-or. Binary bitwise operators are documented here.

Alex Martelli
+13  A: 

It's a bitwise XOR (exclusive OR).

It results to true if one (and only one) of the operands (evaluates to) true.

To demonstrate:

>>> 0^0
0
>>> 1^1
0
>>> 1^0
1
>>> 0^1
1

To explain one of your own examples:

>>> 8^3
11

Think about it this way:

1000  # 8 (binary)
0011  # 3 (binary)
----  # APPLY XOR ('vertically')
1011  # result = 11 (binary)
ChristopheD
A slightly more illustrative example might include both numbers having `1` in the same bit to make it clear that `1 xor 1 = 0`.
Mike Graham
+8  A: 

It invokes the __xor__() or __rxor__() method of the object as needed, which for integer types does a bitwise exclusive-or.

Ignacio Vazquez-Abrams
+1 for pointing out what it *really* does, outside of the integer operation.
Mike DeSimone