Interchanging 2 variables without the use of a third
March 9th, 2009
One of the interesting problems witch every programmer is faced when target device do not have so many memory availble is to interchange 2 variables widthout using a third one:
Theory:
| a | b | a XOR b |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
.
| a | 0101 |
| b | 0011 |
| a = a XOR b | 0110 |
| b = a XOR b | 0101 |
| a = a XOR b | 0011 |
a = a ^ b; // a will contain a xor b = 6
b = a ^ b; // b will receive 6 xor 3 = 5
a = a ^ b; // a will become 6 xor 5 = 3
b = a ^ b; // b will receive 6 xor 3 = 5
a = a ^ b; // a will become 6 xor 5 = 3
other methods:
a = a * b
b = a / b
a = a / b
b = a / b
a = a / b
or
a = a + b
b = a – b
a = a – b
b = a – b
a = a – b
Every one is ok to use but if you want to program a microcontroller first one is perfect becouse use basic CPU operations XOR and is very fast.
