Could you please explain how the following assembler code works?
xor ebx, ebx;
mov bl, byte ptr[ecx];
cmp ebx, 0;
I don't get it why you move byte to bl
and afterwards you compare ebx
and not bl
.
bl
is the name of the low 8 bits (bits 7-0) in the ebx
register. There is also bh
which is the bits 15-8 of ebx
, and bx
is the low 16 bits (bits 15-0). There is no name for the higher 16 bits.
This applies to all of the registers eax
, ebx
, ecx
and edx
.
Given that ebx
is first zero'd, the resulting code is probably the consenquence of the compiler doing compiling something like:
char ch;
const char str;
int i;
...
ch = str[i];
if (ch == 0) ...
[Or possibly just if (ch)
].
The extension to 32-bits would be caused by either "saves space" or "runs faster", or the fact that if (ch == 0)
has an int
on the right-hand side and needs to compare the value as int
rather than as char
= byte - I can't say which without seeing the original source code - and even then, the actual code-generation in the compiler quite a complex set of decisions, based on both "what runs fast on which processor" and "correctness according to the language".
This instruction peforms an exclusive-or between all 32 bits of EBX and all 32 bits of EBX, leaving the result in EBX. You can prove easily that this is the same as moving the value of 0 into EBX (but it's faster than doing that because this way there are no memory fetches required)
xor ebx, ebx;
This instruction moves the BYTE (8 bits) at the address pointed to by ECX into the LOW 8 bits of EBX, leaving the other 24 bits unchanged (they're zero - remember?)
mov bl, byte ptr[ecx];
This instruction compares the whole 32-bit value in EBX with 0 - in this case it's logically the same as just comparing the byte in BL with 0 since we know the upper 24 bits will be 0
cmp ebx, 0;
(anticipated) why do it this way?
Because this is a 32-bit processor. It's geared to operate on 32-bit values much more efficiently than 8-bit ones. The compiler knows this and will always seek to promote smaller values to larger ones as soon as it is allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With