- A xor A = 0 for every A

Table of contents |

2 Explanation 3 Code examples 4 Usage in practice |

- copying
*y*aside to a temporary storage area - setting
*y*to be*x* - copying the temporary storage value back to
*x*.

- XOR X and Y and store in X
- XOR X and Y and store in Y
- XOR X and Y and store in X

- X := X XOR Y
- Y := X XOR Y
- X := X XOR Y

- XOR R1, R2
- XOR R2, R1
- XOR R1, R2

- X = 1 1 0 0
- Y = 1 0 1 0

- X = 0 1 1 0
- Y = 1 0 1 0

- X = 0 1 1 0
- Y = 1 1 0 0

- X = 1 0 1 0
- Y = 1 1 0 0

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

- X = x0 XOR y0, Y = y0
- X = x0 XOR y0, Y = x0 XOR y0 XOR y0 = x0 XOR 0 = x0
- X = x0 XOR y0 XOR x0 = x0 XOR x0 XOR y0 = 0 XOR y0 = y0, Y = x0

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.

XOR AX, BX XOR BX, AX XOR AX, BXHowever, all x86 microprocessors have an XCHG instruction which does the same work on its operands more efficiently than the above sequence of XORs.

The following Visual Basic subroutine swaps the values of its parameters using the xor operator.

Sub Swap (Var1, Var2) Var1 = Var1 Xor Var2 Var2 = Var2 Xor Var1 Var1 = Var1 Xor Var2 End Sub

x ^= y; y ^= x; x ^= y;The set-up as a compiler macro is common for extensive use.

#define xorSwap(x,y) {(x)=(x)^(y); (y)=(x)^(y); (x)=(x)^(y);}

As a function:

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).

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 list