[Tutor] xor
Paul Sidorsky
paulsid@shaw.ca
Wed, 05 Jun 2002 18:13:42 -0600
Danny Yoo wrote:
> 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 = a ^ b
> >>> b = a ^ b
> >>> a = a ^ b
In C this is usually condensed to the ugly but very efficient
a^=b^=a^=b, which I first saw in Abrash's Zen of Graphics Programming.
Aside from saving space, it's significantly faster.
Of course, this won't work in Python because a ^= b is an assignment and
assignments don't have values in Python.
--
======================================================================
Paul Sidorsky Calgary, Canada
paulsid@shaw.ca http://members.shaw.ca/paulsid/