AlgoViz

Bitwise XOR

easy 14 min

XOR compares two numbers bit by bit and outputs 1 wherever they differ.

Video lesson · Chapter 1 of 6

One tag misses its partner

0:00 / 5:39

Bitwise XOR

1:26Reel

Read caption

Zee finds the sole unpaired badge in five scans by tracing the ones and zeroes of a single accumulator. Equal bits cancel. Different bits shine.

How it works

Step through the idea, or press Play.

Step 1 of 3

Compare bit by bit. Line up both numbers in binary; each column gives 1 if the bits differ and 0 if they match

Understand it

Start here

What XOR is

XOR, short for exclusive or, is a bitwise operation written ⊕\oplus in maths and ^ in Python, C, Java and JavaScript. It looks at two bits and answers one question: are they different? Different gives 1, the same gives 0. That is why it is often called the difference detector.

The XOR truth table

ABA ⊕ BWhy
000Same bits
011Different bits
101Different bits
110Same bits
Ordinary OR gives 1 for the last row too. XOR excludes the case where both are 1, hence exclusive.

Bit by bit

XOR of two whole numbers

For whole numbers, XOR applies the truth table to every column of their binary forms at once. There are no carries, so each column is independent. (If binary is new, read Number bases first.) Take 5⊕35 \oplus 3: write 5 as 0101 and 3 as 0011, compare the columns, and read the answer 0110, which is 6.

5 XOR 3, column by column

0101(5)⊕0011(3)0110(6)\begin{array}{rccccl} & 0 & 1 & 0 & 1 & (5)\\ \oplus & 0 & 0 & 1 & 1 & (3)\\ \hline & 0 & 1 & 1 & 0 & (6) \end{array}
The 1s in the answer sit exactly where 5 and 3 disagree: the twos column and the fours column.

Deciding one result bit

The processor runs this for every bit position at the same time, in a single instruction.
Python
a, b = 5, 3print(bin(a), bin(b), bin(a ^ b))   # 0b101 0b11 0b110print(a ^ b)                        # 6print(12 ^ 10)                      # 1100 ^ 1010 = 0110 = 6print(7 ^ 7, 7 ^ 0)                 # 0 7
Python's ^ works on any integers; bin() shows the bits.
Edit and run it in your browser

The rules

Four properties that power every trick

Self-cancelling and identity

a⊕a=0a⊕0=aa \oplus a = 0 \qquad a \oplus 0 = a
Every bit of aa matches itself, so all columns give 0. XOR with 0 leaves every bit unchanged.

Commutative and associative

a⊕b=b⊕a(a⊕b)⊕c=a⊕(b⊕c)a \oplus b = b \oplus a \qquad (a \oplus b) \oplus c = a \oplus (b \oplus c)
Order and grouping never matter, so a long chain of XORs can be rearranged freely.

Its own inverse

(a⊕b)⊕b=a⊕(b⊕b)=a⊕0=a(a \oplus b) \oplus b = a \oplus (b \oplus b) = a \oplus 0 = a
XOR with the same value twice undoes it. This is what makes the swap, RAID recovery and simple ciphers work.
  • Self-cancel

    a⊕a=0a \oplus a = 0. Any value XORed with itself vanishes.

  • Identity

    a⊕0=aa \oplus 0 = a. Zero is the safe starting value.

  • Commutative

    a⊕b=b⊕aa \oplus b = b \oplus a. Order does not matter.

  • Associative

    (a⊕b)⊕c=a⊕(b⊕c)(a \oplus b) \oplus c = a \oplus (b \oplus c). Grouping does not matter.

The magic

Why pairs cancel out

Put the four rules together. In a⊕b⊕aa \oplus b \oplus a you may move the two aas next to each other, they become 0, and 0 does nothing: a⊕b⊕a=(a⊕a)⊕b=0⊕b=ba \oplus b \oplus a = (a \oplus a) \oplus b = 0 \oplus b = b. The same works for any list, however the pairs are scattered.

Folding [4, 1, 2, 1, 2]

4⊕1⊕2⊕1⊕2=4⊕(1⊕1)⊕(2⊕2)=4⊕0⊕0=44 \oplus 1 \oplus 2 \oplus 1 \oplus 2 = 4 \oplus (1 \oplus 1) \oplus (2 \oplus 2) = 4 \oplus 0 \oplus 0 = 4
Regrouping is legal because XOR is commutative and associative. The pairs never had to be adjacent.

The running XOR

The variable holds a mix of everything seen so far; each partner removes its twin.

Pattern 1

Find the single number

Given a list where every value appears twice except one, XOR everything into one variable. It is one pass and one integer of memory, which beats the hash set on space.

Python
def single_number(nums):    result = 0    for num in nums:        result ^= num    return resultprint(single_number([4, 1, 2, 1, 2]))   # 4print(single_number([2, 2, 1]))         # 1print(single_number([-3, 7, 7]))        # -3, negatives work too
The XOR accumulator pattern: result ^= num.
Edit and run it in your browser

Three ways to find the single number

ApproachTimeExtra spaceNote
Count with a hash mapO(n)O(n)Works for any repeat count
Sort, then scan pairsO(n log n)O(1) to O(n)Changes or copies the input
Running XORO(n)O(1)Needs exact pairs

Pattern 2

Find the missing number

An array of nn values holds every number from 00 to nn except one. The full list 0,1,…,n0, 1, \dots, n is what should be there; nums is what is there. XOR both together: every present number appears twice and cancels, and the missing one is left alone.

Missing number in one line

missing=⨁i=0ni  ⊕  ⨁nums\text{missing} = \bigoplus_{i=0}^{n} i \;\oplus\; \bigoplus \text{nums}
For [3,0,1][3, 0, 1]: (0⊕1⊕2⊕3)⊕(3⊕0⊕1)=2(0 \oplus 1 \oplus 2 \oplus 3) \oplus (3 \oplus 0 \oplus 1) = 2.

Indexes against values

Each index is a number that should exist; each value is a number that does. Matches cancel.
Python
def missing_number(nums):    n = len(nums)    result = n    for i, num in enumerate(nums):        result ^= i ^ num    return resultprint(missing_number([3, 0, 1]))            # 2print(missing_number([0, 1]))               # 2print(missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1]))   # 8
Seed with n, then cancel index against value.
Edit and run it in your browser

Pattern 3

Swap without a temporary variable

a = 5, b = 3

  1. 1

    a ^= b

    a becomes 5⊕3=65 \oplus 3 = 6, a value that encodes both originals.

  2. 2

    b ^= a

    b becomes 3⊕6=b⊕(a⊕b)=a=53 \oplus 6 = b \oplus (a \oplus b) = a = 5. The two bbs cancel.

  3. 3

    a ^= b

    a becomes 6⊕5=(a⊕b)⊕a=b=36 \oplus 5 = (a \oplus b) \oplus a = b = 3. The two aas cancel.

Values after each XOR

At no point is a value lost, because each step can be undone by repeating it.

Masks

Flipping and finding bits

XOR with a mask flips exactly the bits that are 1 in the mask and leaves the rest alone, because x⊕1=¬xx \oplus 1 = \lnot x and x⊕0=xx \oplus 0 = x for a single bit. That makes it the tool for toggling flags and for spotting where two numbers differ.

XOR and friends in one table

PatternCodeWhat it does
Accumulateresult ^= numFold a list; pairs cancel
Swapa ^= b; b ^= a; a ^= bExchange two values without a temp
Toggle bit kx ^= 1 << kFlip one bit, leave the rest
Isolate lowest set bitx & -xKeep only the rightmost 1 (12 → 4)
Mark lowest set bit and belowx ^ (x - 1)Rightmost 1 and every bit under it set (12 → 7)
Differ test(a ^ b) != 0True when a and b differ anywhere
Hamming distancebin(a ^ b).count("1")How many bit positions differ
Careful with the last two: x ^ (x - 1) does not toggle one bit, it builds a mask of the rightmost 1 and every bit below it.
Python
flags = 0b1010flags ^= 1 << 0          # turn bit 0 onprint(bin(flags))        # 0b1011flags ^= 1 << 0          # and off againprint(bin(flags))        # 0b1010x = 12                   # 0b1100print(x & -x)            # 4, the lowest set bitprint(x ^ (x - 1))       # 7, that bit and everything below itprint(bin(9 ^ 14).count("1"))   # 3 bits differ between 1001 and 1110
Masks in action.
Edit and run it in your browser

Going further

Two single numbers at once

If two values appear once and the rest twice, XORing everything gives x=a⊕bx = a \oplus b, not either value. But x≠0x \ne 0, so aa and bb differ in at least one bit. Pick one such bit with x & -x, split the list by that bit, and XOR each group: each group holds one single plus whole pairs.

Splitting by a differing bit

Pairs always land in the same group, because twins have identical bits, so they still cancel.
Python
def two_singles(nums):    x = 0    for num in nums:        x ^= num    diff = x & -x    a = b = 0    for num in nums:        if num & diff:            a ^= num        else:            b ^= num    return sorted([a, b])print(two_singles([1, 2, 1, 3, 2, 5]))   # [3, 5]
Two passes, O(1) space.
Edit and run it in your browser

In real systems

Where XOR shows up

  • RAID 5 parity

    Parity = D1⊕D2⊕D3D_1 \oplus D_2 \oplus D_3. Lose one drive and XOR the rest to rebuild it.

  • Error detection

    Parity bits, checksums and ECC memory use XOR to notice flipped bits.

  • Ciphers

    One-time pad: message ⊕\oplus key = ciphertext; the same key decrypts. AES and ChaCha20 use XOR at their core.

  • Graphics

    XOR drawing mode: draw a cursor or selection box once to show it, again to erase it, without saving the background.

  • Hashing

    FNV hashing XORs in each byte; Zobrist hashing encodes chess positions as XORs of random keys.

RAID 5 recovering a lost drive

Recovery is the self-inverse rule: XOR out everything you still have and the missing block remains.

Habits

Good and bad XOR habits

Do

  • Start an XOR accumulator at 0, its identity.
  • Seed missing number with n so index n takes part.
  • Use a, b = b, a in production; keep the XOR swap for interviews.
  • Parenthesise mixed expressions: (a ^ b) + 1.

Avoid

  • Writing x ^ 2 for a square: that is XOR, not a power.
  • Using the pair trick when values repeat three times.
  • XOR-swapping arr[i] with arr[j] without checking i != j.
  • Expecting 32-bit wraparound from Python ints without a mask.

Recap

Key takeaways

Key points

  • XOR outputs 1 where bits differ and 0 where they match: same is zero, different is one.
  • Four rules: a⊕a=0a \oplus a = 0, a⊕0=aa \oplus 0 = a, commutative and associative.
  • Together they make pairs cancel anywhere in a list, so a running XOR finds the single number in O(n) time and O(1) space.
  • Missing number: ⨁i=0ni⊕⨁nums\bigoplus_{i=0}^{n} i \oplus \bigoplus \text{nums} leaves only the absent value.
  • XOR is its own inverse: (a⊕b)⊕b=a(a \oplus b) \oplus b = a, which powers the swap, RAID parity and one-time pads.
  • XOR with a mask flips chosen bits; x & -x isolates the lowest set bit for splitting problems.
  • Limits: only even repeats cancel, the XOR swap fails on the same memory, and ^ is never a power.

Sources