Assembly XOR Instruction

In x86-64 assembly, the XOR instruction performs a bitwise exclusive OR operation between two operands. The result of XOR is true if the values are unequal, and false when they are equal.

XOR takes two operands and stores the result in the first operand. The general syntax of the XOR instruction is:

xor destination, source

Here, destination is the destination operand, and source is the source operand. The xor instruction computes the bitwise XOR of the destination operand and the source operand, and stores the result in the destination operand.

One of the most common uses of XOR is in setting registers equal to zero.

How Exclusive Or (XOR) Works

Exclusive OR (XOR) is a binary operation that takes two equal-length binary representations and performs a logical XOR operation on each pair of corresponding bits.

XOR returns a 1 if the bits are different, and 0 if they are the same.

Here’s how XOR works on a single bit:

  • 0 XOR 0 = 0
  • 1 XOR 0 = 1
  • 0 XOR 1 = 1
  • 1 XOR 1 = 0

We can see that XOR is similar to an OR operation, but is false when both inputs are true.

This can also be understood using a logic table.

XOR Logic Table

Input AInput BOutput
000
101
011
110

For example, consider the XOR operation on two 8-bit binary numbers, 11001100 and 10101010:

    11001101
XOR 10101010
-----------
01100111

Each bit of the result is obtained by applying the XOR operation to the corresponding bits of the two input numbers.

Set a Register to Zero Using XOR

XOR is the most common, reliable, and best way to set a register equal to zero. It’s the officially recommended method by AMD and Intel to zero out a register, and it takes advantage of the fact that if we xor a value with itself we will always get zero.

It is good practice to zero out registers before using them.

One important thing to note is that when we use the XOR instruction on a 32-bit register, it will automatically zero-out the upper 32 bits. For this reason, it is most efficient to use 32-bit registers rather than the full 64-bit register.

For example, we use XOR to zero out the rax register:

xor eax, eax

After the xor instruction, rax would contain 0, because XORing a value with itself results in 0.

This is slightly more efficient than using rax directly:

xor rax, rax