Hello I wrote 2 programs I that should invert a sring. The first one works but I made a second one which should be faster I believe but that one doesn't work completely. Can anyone tell me what's going wrong?
And any suggestions on even better ways to implement this?
Version1: (outputs Hello World! as expected)
.386
.model flat, stdcall
option casemap :none
include \masm32\include\kernel32.inc
include \masm32\include\masm32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\masm32.lib
.data
HelloWorld db "!dlroW olleH", 0
.code
start:
mov esi,offset HelloWorld
loop1:
mov al,[esi]
or al,al ;if al is zero then the zero flag will be set.
jz invert
push ax
inc esi ;go to next character
jmp loop1
invert:
mov esi,offset HelloWorld
loop2:
mov al,[esi]
or al,al
jz finished
pop ax
mov [esi],al
inc esi
jmp loop2
finished:
invoke StdOut, addr HelloWorld
invoke ExitProcess, 0
end start
Version2: (outputs Hello World!dlr for some reason)
.386
.model flat, stdcall
option casemap :none
include \masm32\include\kernel32.inc
include \masm32\include\masm32.inc
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\masm32.lib
.data
HelloWorld db "!dlroW olleH", 0
.data?
inv db ?
.code
start:
mov esi,offset HelloWorld
mov edi,offset inv
push esi
loop1:
mov al,[esi]
or al,al ;if al is zero then the zero flag will be set.
jz invert
inc esi ;go to next character
jmp loop1
invert:
dec esi
pop eax
loop2:
mov edx,[esi]
mov [edi],edx
cmp eax,esi
jz finished
dec esi
inc edi
jmp loop2
finished:
invoke StdOut, addr inv
invoke ExitProcess, 0
end start
If there's something you don't understand then feel free to ask it.
Thanks in advance,
Jannes
Jannes,
This solves your problem:
finished:
mov byte ptr [edi], 0
invoke StdOut, addr inv
You need to delimit the string, that's all.
You can achieve the same with either of these two changes:
loop2:
movzx edx, byte ptr [esi] ; make sure dh is zero
mov [edi], dl ; make sure you don't move dh into the zeroed memory
That makes it three options :P
P.S.: A dedicated thread on string reversing (http://www.masmforum.com/board/index.php?topic=14041.msg111279#msg111279)
the "inv" buffer should be as long as the "HelloWorld" string
.data
HelloWorld db "!dlroW olleH", 0
.data?
inv db sizeof HelloWorld dup(?)
Oh and another minor error:
I shouldve had this:
loop2:
mov edx,[esi]
mov [edi],edx
cmp esi,eax
jc finished