YoYo Games Wiki

XOR Swap Algorithm

From YoYoGames Wiki

When programming something as computationally expensive as a video game, it is often desirable to use as few variables as possible. In this respect, it is possible, though not always beneficial, to swap the value of two variables without using a buffer and using only a few simple xor calls. Note that in Game Maker or on most any modern processor one might as well simply use a buffer as xor swapping will most likely be slower (due to the rise of parallel pipelines), however, this article may provide some insite to new programmers as to the practical application of bitwise operations.

To swap two variables using xor we can use the following pseudo-code algorithm:

  var a, b;
  a = some_value;
  b = some_value;
  // Swap 'a' and 'b'
  a = a xor b;
  b = a xor b;
  a = a xor b;

Proof of Concept: Xor both shares the properties of Abelian groups and is its own inverse. This makes it possible to swap two variables using only xor calls so long as the two input variables do not point to the same memory address in which case the data will be lost. (This means you can not xor swap a variable with itself which is a direct result of the xor operation being its own inverse.) Also note that this code can only be used if both variables store the same basic data type.