XCHG Instruction in Assembly

In x86-64 assembly, the xchg instruction exchanges the contents of two operands.

Short for ‘exchange’, xchg can be used to swap the values of two registers or a register and a memory location.

The syntax for xchg is:

xchg <operand_1>, <operand_2>

Following this operation, the value operand_1 will be equal to the initial value of operand_2, and the value of operand_2 will be equal to the initial value of operand_1.

Like the MOV instruction, the primary purpose of XCHG is to move data from one place to another. In fact, we could perform the function of xchg using MOV and three registers or memory locations. This is where the value of xchg is found. It allows us to swap two values without having to use a third register and in a single line of code.

Exchanging Two Registers

For example, to swap the contents of the rax and rbx registers, you would use:

xchg rax, rbx

Let’s see a simplified example to see how this works:

mov rax, 0 ; set rax to 0
mov rbx, 1 ; set rbx to 1
xchg rax, rbx ; exchange

In this example, rax is initially set to 0, and rbx is set to 1. Following the xchg instruction, rax will store the value 1, and rbx will be 0.

Exchanging A Register and a Memory Location

The xchg instruction can also be used to swap the contents of a register with a memory location. In the following example, we exchange the value of the rax register with that of the memory location pointed to by rdi:

xchg rax, [rdi]

Note that we are using the square-bracket notation here to specify that we are using a pointer. In other words, we want to pull the value from the memory location specified by [rdi] (not the value of rdi, which should be holding an address in memory).