How to convert an integer to string in Assembly 8086

1.7k views Asked by At

I am trying to create a function that gets a parameter in hexadecimal and a char*.
I am trying to turn the parameter to a string and then append it to the char*.

This is my code:

wordToString PROC
    push bp                 
    mov bp,sp
    
    xor cx,cx
    mov bx, 10
    
    loop1:   
    mov dx, 0     
    mov ax, [bp+6]
    div bx
        
    mov [bp+6][cx], dx
    call print_al_chr
        
    inc cx   
    cmp cx,4 
    jle loop1
    
    
    mov sp,bp 
    pop bp   
    ret 2

    
wordToString ENDP

main:
    lea dx, array
    mov ax, num1
    
    push dx
    push ax  
    
    call wordToString
1

There are 1 answers

0
Fifoernik On
mov ax, [bp+6]

The parameter num1 was pushed last and thus is closest to the return address on the stack available at [bp+2]. Therefore you need to write mov ax, [bp+4]
Also you retrieve this value within the loop and thus you'll end up with 5 identical divisions. Move it to before the loop and make sure you don't modify AX other than by the div instruction.


ret 2

You pushed 2 words on the stack, and so you need to remove 4 bytes upon returning. Write ret 4


mov [bp+6][cx], dx

This can't be a valid instruction!
You need to fetch the pointer to the array before starting the loop and then within the loop you increment this value.

;Before the loop
mov  di, [bp+6]
...
;Within the loop
mov  [di], dl            <<< Use DL, a byte in the range [0,9]
inc  di
...
inc  cx
cmp  cx,4 
jle  loop1               <<< Does 5 iterations because of JLE
                         <<< For 4 iterations you would use JL