Assembly, printing ascii number

Solution 1:

Something like this would work better for printing a decimal value (the new code is in lowercase):

        mov byte [buffer+9],'$'
        lea si,[buffer+9]

        MOV AX,CX           ;CX = VALUE THAT I WANT TO CONVERT
        MOV BX,10         
ASC2:
        mov dx,0            ; clear dx prior to dividing dx:ax by bx
        DIV BX              ;DIV AX/10
        ADD DX,48           ;ADD 48 TO REMAINDER TO GET ASCII CHARACTER OF NUMBER 
        dec si              ; store characters in reverse order
        mov [si],dl
        CMP AX,0            
        JZ EXTT             ;IF AX=0, END OF THE PROCEDURE
        JMP ASC2            ;ELSE REPEAT
EXTT:
        mov ah,9            ; print string
        mov dx,si
        int 21h
        RET

buffer: resb 10

Instead of printing each character directly it adds the characters to a buffer in reverse order. For the value 123 it would add '3' at buffer[8], '2' at buffer[7] and '1' at buffer[6] - so if you then print the string starting at buffer+6 you get "123".
I'm using NASM syntax but hopefully it should be clear enough.

Solution 2:

As Michael has written in his code, you need to clear DX , ie make it 0 before you divide.

But if you ask me, if you only need to display a number in the ASCII form (not get a smiley face when you want a number to be displayed). Converting the value to ASCII internally can be quite inconvenient.

Why don't you just use an array defined in the start of the program that has all the ASCII values of the numbers and pick the one that is corresponds to.

for eg. DB arr '0123456789' and compare each number with the particular position and print that one. It's been a really long time since I've coded in 8086 but I remember using this logic for a program which required me to print an ASCII value of a hex number. So i used an array which had 0123456789ABCDEF and it worked perfectly.

Just my two cents. Since you only wanted the result. doesn't really matter how you compute it.