Bilal Mirza
Bilal Mirza

Reputation: 233

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

Upvotes: 1

Views: 22412

Answers (2)

Kauno Medis
Kauno Medis

Reputation: 93

When the number is bigger and positive, and using only BIOS (or output to some other port) try this method using stack as memory:

        push 0x29 ;just marker
        
        ;AX number must be here...
.l1     mov bx,10
        mov dx,0
        div bx
        add dx,48 ;convert to ASCII
        push dx  ;store the string
        cmp ax,0
        jnz .l1
        
.l2     pop ax
        cmp AX,0x29 ;we have marker?
        jz .l3
        call print_char_al ; print ASCII value in AL using BIOS or sent to port
        jmp .l2
.l3     ret

Upvotes: 0

Sep Roland
Sep Roland

Reputation: 39166

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

Upvotes: 2

Related Questions