I will show you how it's possible to write it in C in different way. If you can understand what I did, you should be able to do your asm loop later once you get a bit better accustomed to the computer memory design and how CPU works with it.
void reverse(int len, char *str) {
char *bptr = str;
char *eptr = str+len-1;
char temp;
while (bptr < eptr) {
temp = *bptr;
*bptr = *eptr;
*eptr = temp;
++bptr;
--eptr;
}
}
The loop body of this C can be converted into ASM by using exactly one x86 instruction for each line, and the initial while
can be done by using two instructions ahead of loop body and one instruction after it.
You should be able to write all this with only mov
, inc
, dec
, cmp
, jae
, ret
and lea
or add
.
BTW, if you want to learn ASM, don't memorize "how to write loop" by instructions, like some kind of source listing, that's completely useless. You need to memorize (1) what exactly each instruction does, and understand how the loop is achieved through that.
The CPU is deterministic state machine, and each instruction does change that state in simple deterministic manner. So at the start you have CPU in some state, and memory in some state (containing probably some input data, and also your instructions = code), and you know what state you want to achieve at the end (both state of CPU and memory content). And you simply use instructions to change that initial state into the ending state.
If for example your initial state is that ax
contains value 5, and you want end with ax
containing value 6
, you have several ways how to achieve that, shorter ones (each has only single instruction) being:
mov ax,6
mov al,6
inc ax
inc al
Ridiculous way wasting many instructions can be:
xor ax,ax
dec ah
shr ax,14
add ax,ax
That's why memorizing "listings" is useless, there are many many ways how to achieve the state you want.
(1) not exactly, I'm still checking the Intel instruction reference guide almost every time I write some ASM, even after 20+ years of knowing x86 asm. Because often the details matter and I have to be sure the instruction will do exactly what I expect it to do.