typestar

print_decimal.asm in Assembly

Unsigned to decimal: divide by ten, build the digits backward.

; Print an unsigned number in decimal: divide by 10, push digits.

        global _start

        section .bss
buf:    resb 24                 ; plenty for a 64-bit decimal

        section .text
; rdi = number -> writes digits + newline to stdout
print_u64:
        lea rsi, [buf + 23]     ; build from the right
        mov byte [rsi], 10      ; trailing newline
        mov rax, rdi
        mov rcx, 10
.digit:
        xor rdx, rdx
        div rcx                 ; rax = quot, rdx = digit
        add dl, '0'
        dec rsi
        mov [rsi], dl
        test rax, rax
        jnz .digit

        lea rdx, [buf + 24]     ; length = end - start
        sub rdx, rsi
        mov rax, 1
        mov rdi, 1
        syscall                 ; rsi already points at the digits
        ret

_start:
        mov rdi, 0
        call print_u64          ; edge case: a lone zero

        mov rdi, 42
        call print_u64

        mov rdi, 1234567890
        call print_u64

        mov rax, 60
        xor rdi, rdi
        syscall

How it works

  1. Digits emerge in reverse; the buffer fills right to left.
  2. div rcx peels one digit into rdx each pass.
  3. The zero edge case prints before the loop would run.

Keywords and builtins used here

The run, in numbers

Lines
43
Characters to type
792
Tokens
115
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 125 seconds.

Type this snippet

Step 1 of 3 in Encore, step 29 of 31 in Language basics.

← Previous Next →