Right now, the only printing we can do is of fixed strings, by using the write syscall. We’ll extend this by writing our own code to print 64-bit unsigned integer values. This essentially involves converting a binary value to decimal, using the same procedure we used to convert to binary/hexadecimal: divide repeatedly by 10 and look at the remainders.

Converting binary to decimal

As with converting decimal to binary, we divide repeatedly (by 10 this time) and use the remainders for the digits. E.g., to convert 101101b to decimal:

Binary Remainder Decimal
101101b 5 _5
100b 4 45
0b 45

We stop when we get to 0.

Digits are written in reverse, from the right end of the string.

In order to perform the conversion, we will need to pre-allocate a string buffer big enough to hold all the digits of the biggest unsigned 64-bit integer, 18446744073709551615, 20 characters:

section .data

BUFLEN:     equ                20
buffer:     times BUFLEN db    0    ; Buffer of 20 '\0's

(We could also use the .bss section, which is specifically used for uninitialized space, since we don’t really need to fill the buffer with 0s.)

Your code should assume that the value to be converted is stored in register rdi, and the file number to write to in register rsi; it should construct the character representation in the buffer and then call the write syscall to print it to the file number in rsi.

Use the following template for your program:

section .data

BUFLEN:     equ                20
buffer:     times BUFLEN db    0    ; Buffer of 20 '\0's
newline:    db                 10   ; Single newline

section .text

global _start
_start:

    mov rsi, 1
    mov rdi, 10
    call print_int

    mov rsi, 1
    mov rdi, 186562354
    call print_int

    mov rsi, 1
    mov rdi, 0xdeadbeef12345678         ; = 16045690981402826360 decimal
    call print_int

    ; End program
    mov     rax,  60 
    mov     rdi,  0 
    syscall

print_int:

    ; Your printing code here 

    ret         ; Return from print_int function

Output

The output of your program should look something like this:

00000000000000000010
00000000000186562354
16045690981402826360

The leading 0s on each number are fine.

For a challenge, try to implement this using only loop for iteration (i.e., no jmp or jCC instructions).