I'm trying to check if a value is zero in x86_64 assembly code. I know that this usually consist of a cmp variant followed by a jmp variant, but I'm not sure of the exact instructions to use.
Asked
Active
Viewed 3.6k times
8
vhu
- 12,244
- 11
- 38
- 48
Jack Maloney
- 527
- 2
- 5
- 18
-
What is the type of variable? – GJ. Apr 21 '15 at 08:07
2 Answers
17
If you've just used an instruction that modifies ZF before, simply check that flag and jump using JZ or JE. For example
and rax, rbx ; ZF was modified
jz is_zero ; so to check if rax is zero, a single jump is enough
If ZF was not set, you need to do that explicitly. The obvious way is
cmp rax, 0
je equal_zero
However since cmp is longer if you look at the output binary, test or sometimes and, or is preferred
83F800 cmp eax, 0
09C0 or eax, eax
85C0 test eax, eax
The resulting code will be
test rax, rax
jz is_zero
You can get the assembly output from a compiler and check or view it in an online tool like gcc godbolt
Read more: http://en.wikibooks.org/wiki/X86_Assembly/Control_Flow
phuclv
- 37,963
- 15
- 156
- 475
16
test %eax, %eax ; set ZF to 1 if eax == 0
je 0x804f430 ; jump to 0x00804f4 if ZF == 1
ZF is a single bit zero flag which will be set to 1 if eax be equal to zero. je will take the jump to 0x804f430 if the ZF be set to 1.
Tim Biegeleisen
- 502,043
- 27
- 286
- 360
-
1Your answer is correct. Another correct answer is to replace the `test` with `cmp $0, %eax`. – Nayuki Apr 21 '15 at 03:14
-
5@NayukiMinase test is shorter than cmp http://stackoverflow.com/questions/147173/x86-assembly-testl-eax-against-eax?rq=1 – phuclv Apr 21 '15 at 04:10
-
3`jz` might be a more mnemonic choice. (Of course it's the same instruction.) – gsg Apr 21 '15 at 05:03
-