The ^ operator

Peter Hansen peter at engcorp.com
Mon Sep 26 14:21:20 EDT 2005


Tuvas wrote:
> What exactly does the ^ operator do? I've seen, for example, that
> 3^4=7, 3^5=8. but 3^3=0. Is it just adding them together if they are
> not equal, and if they are equal, outputs 0, or what? Thanks!

It performs an "exclusive-OR" (XOR) operation on the binary data 
corresponding to those values.  Where the boolean AND operation returns 
a 1 where both inputs are 1 and a 0 otherwise, and boolean OR returns a 
1 if either input is 1 but 0 otherwise, the XOR operator returns a 1 if 
the two inputs are different (i.e. one is 0 and the other is 1) but a 0 
if they are the same.

When done on the binary value, each corresponding bit is compared using 
the above logic.  For example, 3 is 0011 in binary, and 4 is 0100, so:

   011 binary for 3
^ 100 binary for 4
   ---
= 111 (which is binary for 7).

(match up the binary digits vertically, so the first digit in the result 
comes from the 0 and the 1 above it, in the two input values).

-Peter



More information about the Python-list mailing list