MyNet
MyNet

Reputation: 15

Parse String to Integer in Assembly

I've code that should parse String format to int but it changes f.e. 0 to 658688 and I don't know what to do with it. Is the lodsd command correct here?

toparse DB 128 dup(?)
mov toparse, "0"

  atoi proc uses esi edx inputBuff:DWORD
mov esi, inputBuff
xor edx, edx
.Repeat
lodsd
.Break .if !eax
imul edx, edx, 10
sub eax, "0"
add edx, eax
.Until 0
mov EAX, EDX
ret
  atoi endp

it returns 658688

Upvotes: 1

Views: 2504

Answers (1)

JBES
JBES

Reputation: 1557

You need to either invoke the atoi proc with the ascii's memory offset or push the offset before calling atoi. Right now esi will just contain the random values that are already in inputbuff.

I have revised the proc so that it will process full strings successfully.

toparse db "12345678",0

;mov toparse,"0" ; Max is 4 bytes so define string above

push offset toparse ; |
call atoi           ; - or: invoke atoi,offset toparse  

...

atoi proc uses esi inputBuff:DWORD ; Generally only need to preserve esi, edi and ebx
mov esi,inputBuff
xor edx,edx
xor eax,eax         ; Clear register
.Repeat
lodsb               ; Get one byte
.Break .if !eax
imul edx,edx,10     ; Multiply total by 10
sub eax,"0"         ; Subtract 48
add edx,eax         ; Add result to the total
.Until 0
mov eax,edx         ; Will result in 00BC614E (hex 12345678)
ret
atoi endp

Upvotes: 1

Related Questions