2

I am making atoi function for assembly.
Whatever I try it doesn't work and I have no idea why.

Does anyone know what is the problem?

org 100h

mov si, stri     ;parameter
call atoi        ;call function
pop eax          ;result
mov [broj], eax  ;save
mov ah, 9        ;display (in ascii, because I don't have itoa function yet either)
mov dx, broj
int 21h

mov ah, 8
int 21h
int 20h

atoi:
    mov eax, 0 ;stores result
    mov ebx, 0 ;stores character
atoi_start:
    mov bl, [si] ;get character
    cmp bl, '$' ;till dollar sign
    je end_atoi
    imul eax, 10 ;multiplu by 10
    sub bl, 30h ;ascii to int
    add eax, ebx ;and add the new digit
    inc si ;;next char
jmp atoi_start
end_atoi:
    push eax ;return value
    ret

stri db '1000$'
broj: db ?,?, '$'
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
zoran404
  • 1,682
  • 2
  • 20
  • 37
  • Define "it doesn't work". – Michael Oct 28 '13 at 19:34
  • Maybe you should add some details on the Architecture and assembler used. – user2859193 Oct 28 '13 at 19:37
  • What does "it doesn't work" mean? Does it crash? Hang? Produce the wrong result? Have you single-stepped it to examine the registers? For sure it's not going to output anything meaningful. It will output the characters 0xE8 and 0x03 which, depending on your console display mode, will be either garbage or completely unreadable. You'll have to examine the registers or write an `itoa` so you can see the result. – Jim Mischel Oct 28 '13 at 19:37
  • @user2859193: It's x86 assembly, and calling DOS interrupts (int 21h). – Jim Mischel Oct 28 '13 at 19:38
  • As far as i understand you do int 21h with parameter 9 meaning string output but you don't have a string. Maybe http://stackoverflow.com/questions/4244624/print-integer-to-console-in-x86-assembly helps with the itoa. – user2859193 Oct 28 '13 at 19:48

1 Answers1

3

The problem is that you push eax to the stack just before returning from atoi. ret uses data from top of the stack as a return address. Possible solution: don't push eax to stack and simply return from atoi with the answer in eax. So, you would not need pop eax in the main part of the code.

Besides this, you would also need to be sure that DS points to the code segment where your stri memory location resides. For a regular exit from the program use int 21 function 4Ch. Use of int 20 is deprecated after MS DOS 2.0.

Igor Popov
  • 2,588
  • 17
  • 20