I'm using x86 assembly with the Irvine library.
What's the easiest way to check if a register value is equal to zero or not?
I used cmp instruction but i'm searching for alternative way. This is my code using cmp instruction and the register is ebx
cmp ebx,0
je equ1
mov ebx,0
jmp cont
equ1:
mov ebx,1
jmp cont
cont:
exit
This "booleanizes" a value, producing a 0 or 1 like int ebx = !!ebx
would in C.
Probably the "easiest", or simplest, "not-caring about details" answer how to determine is:
There's a detailed answer from Peter Cordes to "
testl
eax against eax?" question reasoning about flags being set, etc. Also has a link to yet another similar answer, but reasoning about why it is best way from performance point of view. :)How to set some other register (I will pick
eax
) to 1 whenebx
is zero, and to 0 whenebx
is non-zero (non destructive way forebx
itself):Or how to convert
ebx
itself into 1/0 whenebx
is zero/non-zero:Or how to convert
ebx
itself into 1/0 whenebx
is zero/non-zero, other variant (faster on "P6" to "Haswell" cores):etc, etc... It depends what happens before your testing, and also what you really want as output of test, there're many possible ways (optimal for different situations, and optimal for different target CPU).
I will add few more extremely common situations... A counter-loop down-counting from N to zero, to loop N times:
How to process 5 elements of
word
(16b) array (accessing them in array[0], array[1], ... order):One more example, I somehow like this one a lot:
How to set target register (
eax
in example) to ~0 (-1)/0 whenebx
is zero/non-zero and you already have value1
in some register (ecx
in example):The -1 may look as practical as 1 (for indexing purposes at least), but -1 works also as full bitmask for further
and/xor/or
operations, so sometimes it is more handy.