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=====
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:
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: