Beetwise

Bitwise XOR

The XOR operation compares the two values bit by bit.

A bit in the result has the value 1 if the two inputs differ at that position.

XOR is the operation that flips one or more bits.

Try it

The result of 12 XOR 10. Select a bit to change it. Change the bit width or the signed mode to see the effect.

Name or expression
ID0
Binary
0b
Hex
0x
Decimal
ASCII
·
Shift
Sign
Bits
Endian
7
6
5
4
3
2
1
0

Worked example

Calculate 12 XOR 10:

  1. Write the first value: 1100.
  2. Write the second value: 1010.
  3. Set each position where the two values differ.
  4. The result is 0110, which is 6.

Where this is used

A toggle of a status LED is an XOR with the mask of that bit.

A simple checksum uses XOR over all the bytes of a message.

A second XOR with the same mask restores the original value.

Points to note

  • XOR with the same value twice gives the original value. This is the reason XOR suits a toggle.
  • XOR with 0 does not change the value. XOR with a mask of all ones inverts the value.
  • A XOR checksum does not detect a swap of two bytes.

The full tool

The full editor holds many values at the same time. It also evaluates expressions across them, and it reads live values from a serial port.

Open the full editor

Questions

What is 12 XOR 10?
The result is 6. The bits differ at positions 1 and 2, which gives 0110.
How do I flip one bit?
Apply XOR between the value and a mask that has only that bit set. In C this is value ^= mask.
Why is XOR used for a checksum?
XOR is fast and needs no extra memory. It detects a change of a single bit.