DrawCode Algorithm Visualizer • Bit Manipulation • Easy

XOR Swap

Tags: Bit, XOR, Swap, Trick

1. One-Liner

Use a ^= b; b ^= a; a ^= b to exchange values without a temporary—pure XOR algebra.


2. The Problem It Solves

Micro-optimization curiosity, embedded registers, understanding XOR properties—not always faster than modern compiler swap.


3. The Core Idea

Since x^x=0 and x^0=x, chaining XORs toggles bits to carry values across variables—fails if a and b alias same location.


4. How It Works (Step-by-Step)

StepAction
1Check a and b not same address
2a ^= b
3b ^= a (now holds old a)
4a ^= b (now holds old b)

5. Dry Run Example

5 and 7 swap via XOR toggles—trace bits mentally in interview if asked.


6. Key Properties

PropertyDetail
AliasingUndefined/wrong if &a==&b
IntegersNot for floats directly
CompilerOften uses temp anyway

7. Where It Is Used

Domain / SystemUse
EmbeddedRegister tricks
ObfuscationXOR patterns
TeachingXOR properties

8. Interview Tips

Modern code: prefer std::swap—optimizers know best. Mention add/sub swap overflow risks too.


9. Comparison with Other Algorithms

TechniqueNotes
Temp swapClearer, safe
Arithmetic swapOverflow hazard
Tuple swapPythonic

10. Complexity

----
TimeO(1)
SpaceO(1)

Implementation Example (PYTHON)

def xor_swap(a, b):
    if a is b:
        return a, b
    a ^= b
    b ^= a
    a ^= b
    return a, b

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer