Re: swapping how does it work?
- From: "Roy Fine" <rlfine@xxxxxxxxxxxxxxxxx>
- Date: Fri, 10 Jun 2005 08:51:30 -0400
since the operator ^ is a bitwise operator, you can develop the proof based
on single bit values, then extend it to any bit width operands.
consider the following three step sequence
operation a b
---------- ----- ------
initial 0 1
a ^= b 1 1
b ^= a 1 0
a ^= b 1 0
operation a b
---------- ----- ------
initial 1 0
a ^= b 1 0
b ^= a 1 1
a ^= b 0 1
operation a b
---------- ----- ------
initial 1 1
a ^= b 0 1
b ^= a 1 0
a ^= b 1 1
step 1. (a) will be 0 if the two were originally equal, else (a) will be 1
step 2. (b) will be changed if they were not originally equal
step 3. (a) will be !b if they were originall not equal, else b
after the first set (a) is a flag that determines whether the two bits were
originally equal - now you have the original value of (b) and a flag that
indicates whether the two were originaly equal. the next two step set the
new values of (b) then (a). I first used the method to swap the contents of
the two registers - I was programming in BAL on an IBM 370/165, and accesses
to main memory were VERY slow.
regards
roy fine
"Lawrence Groves" <lgroves@xxxxxxxxxxxxxxxxxxx> wrote in message
news:OUa1%23zZbFHA.2768@xxxxxxxxxxxxxxxxxxxxxxx
> "lallous" <lallous@xxxxxxxx> wrote in message
> news:e%23HiQwYbFHA.2984@xxxxxxxxxxxxxxxxxxxxxxx
> > Hello,
> >
> > If you just expand it a little, it would have became clear:
> >
> >> (a)^=(b); (b)^=(a); (a)^=(b);
> >
> > a = a ^ b;
> > b = b ^ a -> b = b ^ a ^ b -> b = b ^ b ^ a -> b = 0 ^ a -> b = a;
> > a = a ^ b -> a = a ^ b ^ a -> a = a ^ a ^ b -> a = 0 ^ b -> a = b;
> >
> > Thus swapped.
>
> Absolutely fabulous explanation!!!!!!
>
> If I was 'pretty weak' in maths like Jacky, I'd be on the floor now.
>
>
> Here's a simpler example (in binary, given ^ is the XOR operator):
>
> a = 1011
> b = 0110
>
> a^=b (a is now 1101)
> b^=a (b is now 1011)
> a^=b (a is now 0110)
>
> a=0110
> b=1011 (values swapped)
>
> Loz.
>
>
.
- References:
- swapping how does it work?
- From: Jacky Luk
- Re: swapping how does it work?
- From: lallous
- Re: swapping how does it work?
- From: Lawrence Groves
- swapping how does it work?
- Prev by Date: Re: Data aligning
- Next by Date: Re: Performance: Iterating a vector in a loop..
- Previous by thread: Re: swapping how does it work?
- Next by thread: _eh_prolog in msvcrt.dll
- Index(es):
Relevant Pages
|