Bitwise XOR (eXclusive OR)

In short: The bitwise XOR operator (^) compares two numbers bit by bit, setting each result bit to 1 only when the input bits differ. XOR has handy properties (x ^ x is 0 and x ^ 0 is x) used for swapping values and finding a lone unpaired number.

The XOR operation (or exclusive or) takes two bits and returns 1 if exactly one of the bits is 1. Otherwise, it returns 0.

1 ^ 1 → 0 1 ^ 0 → 1 0 ^ 1 → 1 0 ^ 0 → 0

Think of it like a bag of chips where only one hand can fit in at a time. If no one reaches for chips, no one gets chips, and if both people reach for chips, they can't fit and no one gets chips either!

When performing XOR on two integers, the XOR operation is calculated on each pair of bits (the two bits at the same index in each number).

5 ^ 6 # gives 3 # At the bit level: # 0101 (5) # ^ 0110 (6) # = 0011 (3)

Frequently Asked Questions

What does the bitwise XOR operator do?

It compares two numbers bit by bit, producing a 1 where the bits differ and a 0 where they match.

What are common uses of XOR?

Finding the single non-duplicated number in an array, toggling bits, swapping two values without a temp variable, and simple checksums.

What are the key properties of XOR?

x ^ x = 0, x ^ 0 = x, and XOR is commutative and associative, so XOR-ing a list cancels out every value that appears an even number of times.

Last updated: June 17, 2026

. . .