Skip to content
systemcoding.dev
Assembly

Zero a register with xor eax, eax

Zero a register with xor eax, eax: two bytes instead of five, and the 32-bit write clears the upper half of rax too. NASM 2.16, x86-64.

1 min read
Summarize in AI

Setting a register to zero with xor eax, eax is the idiom every compiler emits, and it is a trick worth understanding rather than copying. The 32-bit form encodes in two bytes, while mov eax, 0 takes five because it carries a 32-bit immediate. In 64-bit mode a write to a 32-bit register zeroes bits 63:32 of the full register, so eax clears all of rax. The 64-bit xor rax, rax is a byte longer for the same result.

zero.asmasm
bits 64
xor eax, eax      ; 31 C0
mov eax, 0        ; B8 00 00 00 00
xor rax, rax      ; 48 31 C0
Text
00000000  31C0              xor eax,eax
00000002  B800000000        mov eax,0x0
00000007  4831C0            xor rax,rax

The catch is that xor writes the flags (ZF set, CF and OF cleared) while mov leaves them alone, so never put it between a cmp and the branch that reads the result. Reach for mov when the flags are live. The encodings above are from the Intel SDM instruction reference, and the disassembly is how ndisasm from NASM 2.16 prints them.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.