[Tutor] xor
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 5 Jun 2002 13:41:45 -0700 (PDT)
On Wed, 5 Jun 2002, Paul Sidorsky wrote:
> Terje Johan Abrahamsen wrote:
>
> > What does really xor do? I tried an example,
> > >>> 30^76
> > 82
> >
> > ^ means xor if I am completely wrong. I don't see any connection
> > between the numbers. Can anyone explain?
>
> XOR works on the binary level. x XOR y is true if and only if x != y,
> where x and y are binary digits (bits). So if we convert your example
> to binary, it makes sense:
>
> 0011110 = 30
> ^ 1001100 = 76
> --------------
> 1010010 = 82
XOR stands for "exclusive or", so you can think of it as the "one, or the
other, but not both" bit operation.
On a tangent note, there's a cute trick that assembly and C programmers
could use with XOR to swap two values around without using a temporary
variable. Here's an interpreter session that shows how it works:
###
>>> a
42
>>> b
24
>>> a = a ^ b
>>> b = a ^ b
>>> a = a ^ b
>>> a
24
>>> b
42
###
(Danny Hillis mentions this trick in his talk with game developers on Dr.
Dobb's Technetcast:
http://technetcast.ddj.com/tnc_play_stream.html?stream_id=220)
But in Python, to swap two values, it's probably just easier to write:
###
>>> a, b = b, a
###
anyway, so the XOR swap trick is much less useful in Python. In other
languages, with unusual constraints, it might be a useful thing to know...
*grin*