Table of contents |
2 Explanation 3 Code examples 4 Usage in practice |
Standard swapping algorithms require the use of a temporary storage area - standard intuitive algorithms to swap x and y involve:
The algorithm
However, the XOR swap algorithm does not -- this algorithm follows (where X and Y are the names of two variables, rather than two values):
The algorithm looks much simpler when it is written in pseudocode.
In general however, if we call the initial value of X = x0 and the initial value of Y = y0. Then, performing the above steps, remembering a XOR a = 0 and b XOR 0 = b
The following code in x86 assembly language uses the xor swap algorithm to swap the value in the AX register with the value in the BX register without using a temporary buffer.
The following Visual Basic subroutine swaps the values of its parameters using the xor operator.
#define xorSwap(x,y) {(x)=(x)^(y); (y)=(x)^(y); (x)=(x)^(y);}
As a function:
Some experienced programmers advise that this technique should not be used in programming, as its effect is not clear unless you already know the trick. However, others remark that its use is acceptable providing that the trick is wrapped in an appropriately named macro such as SWAP or XOR_SWAP, or appropriate commenting of the code is done.
The use of the algorithm is not uncommon in embedded assembly code where often there is very limited space available for temporary swap space, and this form of swap can also avoid a load/store which can make things much faster. Some optimizing compilers can generate code using this algorithm.
This trick could also be used by someone trying to win an Obfuscated C Code Contest.
See also: xor, symmetric difference, xor linked listExplanation
For example, let's say we have two values X = 12 and Y = 10.
In binary, we have
Now, we XOR X and Y to get 0 1 1 0 and store in X. We now have
XOR X and Y again to get 1 1 0 0 - store in Y, and we now have
XOR X and Y again to get 1 0 1 0 - store in X, and we have
The values are swapped, and the algorithm has indeed worked in this instance.Code examples
x86 assembly language
XOR AX, BX
XOR BX, AX
XOR AX, BX
However, all x86 microprocessors have an XCHG instruction which does the same work on its operands more efficiently than the above sequence of XORs.Visual Basic
Sub Swap (Var1, Var2)
Var1 = Var1 Xor Var2
Var2 = Var2 Xor Var1
Var1 = Var1 Xor Var2
End Sub
C
C programming language code to implement XOR swap of x and y: x ^= y;
y ^= x;
x ^= y;
The set-up as a compiler macro is common for extensive use. void xorSwap(int * x, int * y) {
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}
It should be noted that this function will not work if you try to swap something with itself (ie here xorSwap(&var, &var) will fail - it will assign the value zero to var).Usage in practice