Warning:  lots of 0 and 1 ahead.  Typos are lurking...

On Thu, Jul 25, 2002 at 12:08:09AM +0800, Connie Chan wrote:
> In normal case, when we want to swap 2 var, 
> , say $x and $y, we do in this way :
> 
> $z = $x; $x = $y; $y = $z;  # Swapped
> 
> today, I suddenly found a code like this :
> 
> $x ^= $y ; $y ^= $x ; $x ^= $y; # Swapped
> 
> It works !! but how that works ?
> Could anybody tell me ?

XORing a variable twice with the same value restores its original value:

    $a = 0x55
    $b = 0xff

$a xor $b xor $b gives the old $a 
    0x55 xor 0xff xor 0xff is a no-op.

Now, letst do one xor and store this in $a.  No information is lost and
$a now documents the differences between $a_old and $b.

Note that the order in an xor operation is interchangable

    $a xor $b  <=> $b xor $a

So, by doing the xor again, but not storing it in $a and recovering the
initial state, but storing it in $b, we've assigned the initial $a to
$b.

Now, $a still contains the initial differences between the two and $b
contains the initial $a.

Remember, the XORs are interchangeble.  We have the initial $a and the
differences, which must result in the initial $b when XORed.

Assigning the result to $a finishes the swap.

0.  $a = 0x55   => 01010101 binary
    $b = 0xff   => 11111111 binary

1.      $a 01010101
    XOR $b 11111111
    Is     10101010 which goes into $a (These are the differences)


2.      $a 10101010
    XOR $b 11111111
    Is     01010101 which goes into $b ($b now contains $a_initial)


3.      $a 10101010
    XOR $b 11111111
    Is     01010101 which then goes into $a ($a now contains $b_initial)

<voice name="Kelly Bundy">Vioooola!</voice>

Try different numbers like 0x55 vs 0xaa or 0x33 vs 0xaa...
    

It's an old trick from the Assembler times.  XOR was 1cycle op and the
whole thing only needed 2 registers.  The alternative would have been a
3rd register or a memory/stack operation.

Drieux might provide us with some benchmarks about which one's faster
these days... ;-)

-- 
            Well, then let's give that Java-Wussie a beating... (me)

Michael Lamertz                        |      +49 221 445420 / +49 171 6900 310
Nordstr. 49                            |                       [EMAIL PROTECTED]
50733 Cologne                          |                 http://www.lamertz.net
Germany                                |               http://www.perl-ronin.de 

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to