assemblyx86outputdecimal

Printing decimal number in assembly language?


I'm trying to get output in decimal form. Please tell me what I can do to get the same variable in decimal instead of ASCII.

.model small
.stack 100h

.data

msg_1   db   'Number Is = $'
var_1   db   12

.code

add_1 proc
    mov ax, @data
    mov ds, ax
    mov ah, 09
    lea dx, msg_1
    int 21h
    mov ah, 02
    mov dl, var_1
    int 21h
    mov ah, 4ch
    int 21h
add_1 endp

end add_1

Solution

  • These 3 lines that you wrote:

    mov ah, 02
    mov dl, var_1
    int 21h
    

    print the character represented by the ASCII code held in your var_1 variable.

    To print the decimal number you need a conversion.
    The value of your var_1 variable is small enough (12), that it is possible to use a specially crafted code that can deal with numbers ranging from 0 to 99. The code uses the AAM instruction for an easy division by 10.
    The add ax, 3030h does the real conversion into characters. It works because the ASCII code for "0" is 48 (30h in hexadecimal) and because all the other digits use the next higher ASCII codes: "1" is 49, "2" is 50, ...

    mov al, var_1      ; Your example (12)
    aam                ; -> AH is quotient (1) , AL is remainder (2)
    add ax, 3030h      ; -> AH is "1", AL is "2"
    push ax            ; (1)
    mov dl, ah         ; First we print the tens
    mov ah, 02h        ; DOS.PrintChar
    int 21h
    pop dx             ; (1) Secondly we print the ones (moved from AL to DL via those PUSH AX and POP DX instructions
    mov ah, 02h        ; DOS.PrintChar
    int 21h
    

    If you're interested in printing numbers that are bigger than 99, then take a look at the general solution I posted at Displaying numbers with DOS