Binary XOR truth table and bit mask diagram in C

XOR in C: Understand the ^ Bitwise Operator

XOR in C uses the ^ operator to compare corresponding bits in two integer values. A matching pair produces 0; a different pair produces 1. The XOR operator in C works across every bit in the operands, making it useful for masks and bit toggling.

You can read ^ one bit at a time, then apply the same rule to complete binary integers. Unlike ||, it is not a logical OR, and it does not perform exponentiation.

XOR in C: From the truth table to binary integers

The one-bit XOR truth table is:

  • 0 ^ 0 = 0 because the bits match.
  • 0 ^ 1 = 1 because the bits differ.
  • 1 ^ 0 = 1 because the bits differ.
  • 1 ^ 1 = 0 because the bits match.

For multiple bits, C applies this rule to each position. For example:

1100
1010
1000

The top two binary operands represent 12 and 10. Their XOR result is 8 because each pair of corresponding bits produces the result shown below:

1 ^ 1 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1, and 0 ^ 0 = 0.

How the XOR operator in C works on integer values

In C, ^ performs a bitwise operation on integer types. The operator compares the values after the usual integer promotions and returns an integer result. Use unsigned integers when you want bit patterns that are easy to reason about.

This valid C code XORs 12 and 10:

unsigned int result = 12u ^ 10u;

result receives 8. Written with four-bit patterns, the operation is 1100 ^ 1010 = 1000.

You can also use the compound assignment operator ^=. It XORs a value with a mask and stores the result back in that value:

unsigned int flags = 5u;
flags ^= 4u;

Here, 5 is 0101, 4 is 0100, and flags becomes 1, or 0001.

Use the C XOR operator to toggle selected bits

A bit toggle changes 0 to 1 or 1 to 0. To toggle selected bits, create a mask where each 1 marks a bit to change and each 0 marks a bit to leave alone.

For example:

unsigned int value = 0x0Au;
value ^= 0x04u;

value starts as hexadecimal 0x0A, or binary 1010. The mask 0x04 is 0100:

1010 ^ 0100 = 1110

The third bit from the right toggles from 0 to 1, so the result is 0x0E. If the selected bit had started as 1, the same mask would have changed it to 0. A mask with multiple 1 bits toggles multiple positions at once.

XOR properties: identity, self-canceling, and reversibility

Three XOR properties explain why the operator works well for masks:

  • Identity: x ^ 0 = x. A zero bit leaves the corresponding bit unchanged.
  • Self-canceling: x ^ x = 0. Every bit matches itself, so every output bit is zero.
  • Reversible: applying the same mask twice restores the original value: (x ^ mask) ^ mask = x.

Because XOR is also commutative and associative, you can combine masks or change their order without changing the final bit pattern.