Trouble reversing a string in assembly

前端 未结 2 825
孤街浪徒
孤街浪徒 2021-01-07 06:08

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 n

2条回答
  •  感情败类
    2021-01-07 06:45

    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
    

提交回复
热议问题