Things You'll Need:
- A basic understanding of binary numbers
- To know how XOR works
-
Step 1
Understanding XOR:
XOR or Exclusive-Or, is similar to the commonly used INCLUSIVE-Or, except that if both inputs are 1, the output is 0 (as opposed to INCLUSIVE-Or where the value is 1).
This addresses this case where we normally do something like:
int ii1 = 1;
int ii2 = 2;
int tmp;
tmp = ii1;
ii1 = ii2;
ii2 = tmp; -
Step 2
Now, the magic:
A triple XOR performed on two variables will SWITCH THEM!!!
So, in C#:
int ii1 = 1;
int ii2 = 2;
ii1 ^= ii2;
ii2 ^= ii1;
ii1 ^= ii2;
The variables have now been swapped without using a temporary variable!














Comments
pixiemama said
on 10/9/2008 5*
raystarck said
on 6/24/2008 Nice article! keep posting
MARCUS said
on 11/13/2007 THIS ARTICLE IS AMAZING!!!!