Elmo YT
Elmo YT

Reputation: 19

How do I print out two-digit integers in ASM, ( Linux NASM x86_64 )

This is how to print out a number, but how do I print out 2 digit numbers?

section .data
    num: db 9,10

section .text
global _start
_start:
    mov rax,[num]
    add rax,48
    mov [num],al
    mov rax,1
    mov rdi,1
    mov rsi,num
    mov rdx,2
    syscall

    mov rax,60
    mov rdi,0
    syscall

This simply prints out 9, but if I make num 12 it gives me a '<'. I believe it is printing out the ascii character for 60, which is '<'.

Upvotes: 1

Views: 717

Answers (1)

Sep Roland
Sep Roland

Reputation: 39556

mov rax,[num]

Because num just holds a byte, better not read this as a qword. Use the movzx eax, byte [num] instruction. You don't need the movzx rax, byte [num] instruction because all writing to a dword register already zeroes the high dword anyway.

but how do I print out 2 digit numbers?

Next code can do just that, printing numbers from the range [10,99].
Note that there's a placeholder right in front of the newline.

section .data
    num: db 12, 0, 10

section .text
global _start
_start:
    movzx eax, byte [num]  ; Value LT 100
    xor   edx, edx
    mov   ebx, 10
    div   ebx              ; Quotient in EAX, Remainder in EDX
    mov   ah, dl
    add   ax, '00'         ; Convert to ASCII
    mov   [num], ax        ; Stores 'tens' followed by 'ones'
    mov   rax, 1
    mov   rdi, 1
    mov   rsi, num
    mov   rdx, 3           ; 3 instead of 2
    syscall

For a general approach you could first study Displaying numbers with DOS. It explains the methodology, but of course you'll need to adapt the code to 64-bit.
Even better info is at https://stackoverflow.com/a/46301894.

Upvotes: 1

Related Questions