language-icon Old Web
English
Sign In

XOR swap algorithm

In computer programming, the XOR swap is an algorithm that uses the XOR bitwise operation to swap values of distinct variables having the same data type without using a temporary variable. 'Distinct' means that the variables are stored at different, non-overlapping, memory addresses; the actual values of the variables do not have to be different.Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:The binary operation XOR over bit strings of length N {displaystyle N}   exhibits the following properties (where ⊕ {displaystyle oplus }   denotes XOR):A C function that implements the XOR swap algorithm:In most practical scenarios, the trivial swap algorithm using a temporary register is more efficient. Limited situations in which XOR swapping may be practical include:Most modern compilers can optimize away the temporary variable in the three-way swap, in which case it will use the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster. In addition to that, the XOR swap is completely opaque to anyone unfamiliar with the technique.The underlying principle of the XOR swap algorithm can be applied to any operation meeting criteria L1 through L4 above. Replacing XOR by addition and subtraction gives a slightly different, but largely equivalent, formulation:

[ "XOR gate", "Bitwise operation", "XOR linked list" ]
Parent Topic
Child Topic
    No Parent Topic