Doing the XOR Flip

Written by:dimport
Published by:Nightscript
Published on:2003-06-21 07:19:46
Topic:c

Have you ever wanted to switch two variables around, lets say a and b, but all you can do is use the hardway. Heres some ideas on using an XOR Flip to get more elegant results.

e.g.
mp = b;
b = a;
a = temp;

Well due to a cool effect of using XOR you won't have to anymore. Due to lack of a better name I call this method the XOR Flip, you'll see why in a second. So what is this grand thing called the XOR Flip, well here it is.

If you have two variables, lets just call them A and B. If A = 11 and B = 01 then the XOR Flip works like this:

A xor B:
11
^ 01
-----
A=10
B xor A:
01
^ 10
-----
B=11

Wow! now look at that B equals A isn't that crazy? But we're not done yet:
A xor B:

11
^ 10
-----
A=01

Now how crazy is that, A equals B?? This trick is sometimes useful, and it saves memory(if thats even a concern) by not having to create that extra variable temp. So to conclude/summarize:

if A = 11 and B = 01:
A xor B = 10
B xor A = 11 => B = A and that A = B
A xor B = 01

Or that by peforming 3 simple XORs we can make the variables A and B trade places. And to conclude, here is a little C example I put together:

 
#include usualstuff
 

 
int main(int argc,char** argv) {
 
    printf("Before XOR Flip:");
 
    int a = 2394;
 
    int b = 12;
 

 

 
printf("a = %d, b = %d", a, b);
 

 

 
^= b;
 
    b ^= a;
 
    a ^= b;
 

 

 
printf("After XOR Flip:");
 
    printf("a = %d, b = %d", a, b);
 

 

 
return 0;
 
}
 


I hope you all enjoyed this article, Peace!

by: bitshift

This article was originally written by bitshift

This is an article from http://www.osix.net - view the original at: http://www.osix.net/modules/article/?id=145