XOR in C is the caret operator ^. It compares two integers bit by bit and sets a result bit to 1 only where the two input bits differ, so 12 ^ 10 is 6.
#include <stdio.h>
int main(void) {
printf("%d\n", 12 ^ 10); /* 6 */
printf("%d\n", 5 ^ 5); /* 0 */
printf("%d\n", 5 ^ 0); /* 5 */
return 0;
}
Example output: 6, 0 and 5 on separate lines. The rest of this article covers how XOR works, the common patterns (toggling flags, swapping, finding the value that appears once, a toy cipher) and the mistakes that catch people out. For the other five bitwise operators, see bitwise operators in C with examples.
How XOR works: the truth table
XOR means "exclusive or". The result is 1 when exactly one input is 1, and 0 when both inputs are the same.
| a | b | a ^ b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
On whole numbers, C applies that table to every bit position at once. cppreference describes it this way: the operators &, ^ and | first perform the usual arithmetic conversions on both operands, then apply the logic operation to each pair of corresponding bits. Both operands must be of integer type. Take 12 ^ 10:
1100 (12)
^ 1010 (10)
----
0110 (6)
Two properties drive almost every trick with XOR. Any value XOR itself is 0 (x ^ x == 0), and any value XOR 0 is unchanged (x ^ 0 == x). Together they make XOR its own inverse: (x ^ k) ^ k gives back x. XOR is also commutative and associative, so the order in which you combine values does not matter.
XOR operator versus logical XOR in C
C has the logical operators && and ||, but no logical XOR. The caret is always bitwise. That matters when the operands are not exactly 0 or 1:
int a = 1, b = 2;
printf("%d\n", a ^ b); /* 3: both are true, yet the result is non-zero */
printf("%d\n", (!a) != (!b)); /* 0: both true, so not "exactly one" */
The expression !a turns any non-zero value into 0 and zero into 1, so comparing (!a) != (!b) gives a true logical XOR. The same works with !!a != !!b. If every operand is already a comparison result (which is always 0 or 1), a ^ b also behaves logically, for example (x > 0) ^ (y > 0). Do not rely on that for plain integers.
Toggle a bit or a flag with XOR
XOR with a mask flips exactly the bits that are 1 in the mask and leaves the others alone. This is the standard way to toggle a flag stored in an integer:
#define FLAG_BOLD (1u << 0) /* 0001 */
#define FLAG_ITALIC (1u << 1) /* 0010 */
#define FLAG_UNDERLINE (1u << 2) /* 0100 */
unsigned style = FLAG_BOLD | FLAG_UNDERLINE; /* 0101 */
style ^= FLAG_ITALIC; /* 0111: italic on */
style ^= FLAG_ITALIC; /* 0101: italic off */
Running the same line twice restores the original value, because XOR is its own inverse. If you want to force a flag on or off instead of flipping it, use |= to set and &= ~mask to clear.
The same idea flips a single ASCII letter's case. In ASCII, 'A' is 0x41 and 'a' is 0x61, so they differ only in bit 5 (value 0x20). 'A' ^ 0x20 is 'a', and 'a' ^ 0x20 is 'A'. This only holds for the letters A to Z and a to z, so check the range first.
How to swap two variables with XOR in C
int a = 5;
int b = 9;
a ^= b; /* a = 5 ^ 9 = 12 */
b ^= a; /* b = 9 ^ 12 = 5 */
a ^= b; /* a = 12 ^ 5 = 9 */
printf("%d %d\n", a, b);
Example output: 9 5. After the first line a holds a ^ b. The second line computes b ^ (a ^ b), and the b cancels, leaving the old a. The third line does the same in the other direction. No temporary variable is needed.
It has a well-known trap. If you wrap it in a function that takes two pointers and both point at the same object, the value is destroyed:
void xor_swap(int *first, int *second) {
*first ^= *second;
*second ^= *first;
*first ^= *second;
}
int x = 7;
xor_swap(&x, &x); /* x is now 0 */
The first line computes x ^ x, which is 0, and nothing afterwards can bring the value back. Guard with if (first != second) if you must use it. In practice, a plain temporary variable (int tmp = a; a = b; b = tmp;) is clearer, works for every type, and compilers handle it well. Treat the XOR swap as an exercise in how XOR works, not as an optimisation.
Find the one number that appears once
Since x ^ x is 0 and the order does not matter, XORing a whole array cancels every value that appears an even number of times. What remains is the value that appears once:
int numbers[] = {4, 1, 2, 1, 2};
int single = 0;
for (size_t index = 0; index < sizeof numbers / sizeof numbers[0]; index++) {
single ^= numbers[index];
}
printf("%d\n", single);
Example output: 4. Starting single at 0 is correct because 0 ^ x is x. This runs in one pass and uses no extra memory. It only works when every other value appears an even number of times.
XOR as a parity check
XOR of a set of bits is 1 when the number of 1 bits is odd, and 0 when it is even. That is the idea behind a parity bit. You can fold a byte down to its parity by XORing its halves together:
unsigned parity(unsigned char value) {
value ^= value >> 4;
value ^= value >> 2;
value ^= value >> 1;
return value & 1u;
}
For 0xB (binary 1011, three ones) this returns 1. For 0x3 (binary 0011, two ones) it returns 0. Each step combines pairs of bits, so after three steps bit 0 holds the XOR of all eight. The same principle, XOR of data bytes, gives the simple longitudinal checksum used by some serial protocols, but it catches far fewer errors than a CRC or a hash. If you need to verify files, use the checksum tool.
XOR a buffer with a key (a toy cipher)
Because (x ^ k) ^ k == x, applying the same key twice restores the data:
void xor_buffer(unsigned char *bytes, size_t length, unsigned char key) {
for (size_t index = 0; index < length; index++) {
bytes[index] ^= key;
}
}
unsigned char text[] = "AB";
xor_buffer(text, 2, 0x2A); /* 'A' (0x41) becomes 0x6B, 'B' (0x42) becomes 0x68 */
xor_buffer(text, 2, 0x2A); /* back to "AB" */
This is an illustration of the operator, not protection for real data. A single repeated key byte falls to trivial analysis. For real secrets use a vetted cipher. On larely, the encrypt tool runs in your browser.
Precedence: why you should add parentheses
From cppreference's precedence table, == and != are at level 7, & at 8, ^ at 9, | at 10 and && at 11. A lower number binds tighter. So the comparison binds more tightly than ^, which surprises people:
int a = 5, b = 3;
if (a ^ b == 0) { /* parsed as a ^ (b == 0), i.e. 5 ^ 0 = 5: non-zero, so this runs */ }
if ((a ^ b) == 0) { /* intended: 5 ^ 3 is 6, so this does not run */ }
The first condition is meant to test "a and b are equal", yet it runs for these unequal values, and the compiler will not complain. Put parentheses around every bitwise expression that sits next to a comparison. Also note that ^ binds more tightly than | and less tightly than &, so 1 | 2 ^ 3 means 1 | (2 ^ 3), which is 1.
Common mistakes with ^ in C
- Expecting a power.
2 ^ 3is1(binary10XOR11is01), not 8. C has no exponent operator. Usepow()for floating-point results, or1u << nfor a power of two. - Using it on floating-point values. The operands must be of integer type, so
2.5 ^ 1does not compile. - Using it as logical XOR on non-boolean integers. See the section above and normalise with
!first. - Surprises with narrow and signed types. Operands narrower than
int, such ascharandunsigned char, are converted by the usual arithmetic conversions before the operation, so the result ofa ^ bis at least anint. When you store it back into anunsigned char, the value is converted back to that type. Prefer unsigned types for bit work, so that you do not depend on how negative values are represented. - Self-XOR as a zeroing idiom.
x ^ xis always 0, which is why compilers often use that form to clear a register. In C source, writex = 0.
Frequently asked questions
- What is the XOR operator in C?
- The XOR operator in C is the caret, ^. It takes two integer operands and returns a number whose bits are 1 only where the corresponding bits of the operands differ. For example, 12 ^ 10 is 6.
- Is there a logical XOR operator in C?
- No. C has logical && and ||, but no logical XOR. To test that exactly one of two conditions is true, normalise both to 0 or 1 and compare them: (!a) != (!b). Using ^ directly on non-boolean values is a bitwise operation and can give the wrong answer.
- Does ^ mean power in C?
- No. In C the caret is bitwise XOR, so 2 ^ 3 is 1, not 8. C has no exponent operator. Use pow() from math.h for floating-point powers, or a left shift such as 1u << n for powers of two.
- Why does the XOR swap set both variables to 0 sometimes?
- If both names refer to the same object, for example swap(&x, &x), the first step x ^= x sets it to 0, and every later step keeps it at 0. Check that the two pointers differ, or use a temporary variable.
- Can I use ^ on float or double in C?
- No. The operands of ^ must be of integer type, so applying it to a float or double is a compile-time error. Convert to an integer type first, or copy the bytes into an unsigned integer of the same size if you really need to work on the bit pattern.