Trouble reversing a string in assembly

assembly, x86

Solution

The way to reverse a string by swapping characters is to swap the first and last, then the second and next to last, etc. In C, you would write:

for (i = 0; i < len/2; ++i)
{
    c = s[i];
    s[i] = s[len-i-1];
    s[len-i-1] = c;
}

In assembly language, the easiest way is to set up the ESI and EDI registers to point to the start and end of the string, then loop. At each iteration, you increment ESI and decrement EDI. The result looks something like this:

mov ecx, helloLen
mov eax, hello
mov esi, eax  ; esi points to start of string
add eax, ecx
mov edi, eax
dec edi       ; edi points to end of string
shr ecx, 1    ; ecx is count (length/2)
jz done       ; if string is 0 or 1 characters long, done
reverseLoop:
mov al, [esi] ; load characters
mov bl, [edi]
mov [esi], bl ; and swap
mov [edi], al
inc esi       ; adjust pointers
dec edi
dec ecx       ; and loop
jnz reverseLoop

Problem

I am trying to reverse a string in assembly. However my code does not seem to work correctly. I added a newline string for better readability. I am using linux and nasm as compiler. I thought that if I took the values of the adresspointers and switched them at the correct place, the string would eventually be reversed and then get back to normal. This is my code: ``` section .data hello db 'Hello world!' helloLen equ $-hello derp db '=========',10 derplen equ $-derp section .text global main main: mov eax,0 mov ecx,helloLen reverse: ;move pointer mov ebx,hello add ebx,eax push eax ;move pointer mov eax,hello add eax,ecx push ecx ;switch bytes push ebx mov ebx,[ebx] mov [eax],ebx pop ebx mov eax,[eax] mov [ebx],eax ;print text mov eax,4 mov ebx,1 mov ecx,hello mov edx,helloLen int 80h ;Print newline mov eax,4 mov ebx,1 mov ecx,derp mov edx,derplen int 80h ;increment and decrement pop ecx dec ecx pop eax inc eax cmp eax,helloLen jne reverse end: mov eax,1 mov ebx,0 int 80h ``` This is the output I get: ``` Hello world!Hell===== Hello worldellol===== Hello worlllo ol===== Hello worlo w ol===== Hello woo wow ol===== Hello wooooow ol===== Hello wooooow ol===== Helloooooooow ol===== Helloooooooow ol===== Helooowooooow ol===== Heoow wooooow ol===== How o wooooow ol===== ```

Original source