Skip to main content
Be Bitwise
CAssembly Equivalents of C Patterns

Recreating printf in Assembly

printf is probably the most-used function in C. Formats strings, converts integers to decimal, juggles floating-point, dumps the result to stdout. In this lesson we'll build a minimal printf in raw x86-64 assembly, using nothing but the write syscall. Every abstraction stripped away. You'll see exactly what it takes to put text on a terminal.

The write Syscall

Everything that appears on your terminal ultimately goes through one syscall: write. On Linux x86-64:

  • Syscall number: 1 (in rax)
  • File descriptor: rdi (1 for stdout)
  • Buffer address: rsi
  • Byte count: rdx
asm
section .data
hello: db "Hello, World!", 10 ; 10 is newline (0x0A)
hello_len equ $ - hello ; Calculate string length
section .text
global _start
_start:
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd: stdout
lea rsi, [rel hello] ; buffer: address of our string
mov rdx, hello_len ; count: length of string
syscall ; Invoke the kernel
mov rax, 60 ; syscall: exit
xor rdi, rdi ; exit code: 0
syscall

Assemble and run:

bash
nasm -f elf64 hello.asm -o hello.o
ld hello.o -o hello
./hello

This is the absolute minimum program that can produce output. No C runtime, no libc, no printf. Just a direct conversation with the kernel through one syscall instruction.

Writing a String of Known Length

Let's build a helper print_string that writes a null-terminated string to stdout. First we need the length:

asm
; strlen: count bytes until null terminator
; Input: rdi = pointer to string
; Output: rax = length
strlen:
xor rax, rax ; length = 0
.loop:
cmp byte [rdi+rax], 0 ; Check for null terminator
je .done ; If null, we are done
inc rax ; length++
jmp .loop ; Continue scanning
.done:
ret
; print_string: write a null-terminated string to stdout
; Input: rdi = pointer to string
print_string:
push rdi ; Save string pointer
call strlen ; rax = length
mov rdx, rax ; count = length
pop rsi ; buffer = string pointer (was in rdi)
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd: stdout
syscall
ret

Compare this to the C version:

c
void print_string(const char *s) {
write(1, s, strlen(s));
}

Same thing, but every step is right there in front of you: scanning for the null byte, counting, setting up the syscall arguments.

Converting an Integer to Decimal

Here's where it gets interesting. To print 12345, you have to turn it into the ASCII characters '1', '2', '3', '4', '5'. The trick: divide by 10 repeatedly, treating each remainder as a digit.

asm
; print_uint: print an unsigned 64-bit integer to stdout
; Input: rdi = the number to print
print_uint:
push rbp
mov rbp, rsp
sub rsp, 24 ; Buffer for digits (max 20 digits for 64-bit)
mov rax, rdi ; rax = number to convert
mov rsi, rbp ; rsi = one past the end of the buffer
xor ecx, ecx ; rcx = character count
mov r8, 10 ; Divisor = 10
.divide_loop: ; do-while, so 0 still prints one '0'
xor edx, edx ; Clear rdx for division
div r8 ; rax = rax / 10, rdx = rax % 10
add dl, '0' ; Convert remainder to ASCII digit
dec rsi ; Move buffer pointer back
mov byte [rsi], dl ; Store the digit
inc rcx ; count++
test rax, rax ; Is quotient zero?
jnz .divide_loop ; If not, continue dividing
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd: stdout
; rsi already points to the first digit
mov rdx, rcx ; count = number of digits
syscall
leave
ret

The whole thing hinges on div. div r8 divides the 128-bit value rdx:rax by r8, leaving the quotient in rax and the remainder in rdx. Add '0' (48) to the remainder and you have an ASCII digit. Digits arrive in reverse order, least significant first, so we fill the buffer right to left.

You can watch the buffer fill on the Be Bitwise teaching CPU. It's an 8-bit machine with no divide instruction, so the number is 123 instead of 12345 and each divide by 10 is done by taking 10 off one unit at a time. The buffer handling is the same as print_uint: R6 starts one past the end of the buffer at 0xF3 and steps back a byte for every digit. Press Run, turn the speed up, and keep an eye on 0xF0 to 0xF2 in the memory grid. 0x33 ('3') lands at 0xF2 first, then 0x32 ('2'), then 0x31 ('1') at 0xF0, and R6 ends up pointing at the first digit, ready to hand to write.

For the best simulation experience, use a desktop browser.

Assembly

200ms

Registers

R00
0x0000
R10
0x0000
R20
0x0000
R30
0x0000
R40
0x0000
R50
0x0000
R60
0x0000
R70
0x0000
PC0
0x0000
SP255
0x00FF
FLAGS0x00
ZCVN

ALU

Idle

Memory

PCSPWatched
Memory contents — rows indexed by base address, columns by hex offset
Address0123456789ABCDEF
0000000000000000000000000000000000
1000000000000000000000000000000000
2000000000000000000000000000000000
3000000000000000000000000000000000
4000000000000000000000000000000000
5000000000000000000000000000000000
6000000000000000000000000000000000
7000000000000000000000000000000000
8000000000000000000000000000000000
9000000000000000000000000000000000
A000000000000000000000000000000000
B000000000000000000000000000000000
C000000000000000000000000000000000
D000000000000000000000000000000000
E000000000000000000000000000000000
F000000000000000000000000000000000

Pipeline

Cycle 0
Fetch
Decode
Execute
Writeback
→
→
→
No instruction loaded

Compare to the C approach:

c
void print_uint(unsigned long n) {
char buf[20];
int i = 20;
do {
buf[--i] = '0' + (n % 10);
n /= 10;
} while (n > 0);
write(1, &buf[i], 20 - i);
}

Same logic. The assembly just refuses to hide anything from you: the division, the remainder extraction, the ASCII conversion, the buffer bookkeeping.

Handling Signed Integers

For signed integers: check the sign, negate if needed, print the minus sign, then print the absolute value.

asm
section .data
minus_sign: db '-'
section .text
; print_int: print a signed 64-bit integer to stdout
; Input: rdi = the number to print
print_int:
test rdi, rdi
jns print_uint ; If non-negative, just print as unsigned
; Print minus sign
push rdi ; Save the number
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd: stdout
lea rsi, [rel minus_sign]
mov rdx, 1 ; count: 1 byte
syscall
pop rdi ; Restore the number
neg rdi ; Make it positive
jmp print_uint ; Print the absolute value

Handling Format Strings

Real printf walks the format string character by character, hunting for % specifiers. Here's a stripped-down version that handles %d and %s:

asm
; mini_printf: handle %d and %s format specifiers
; Input: rdi = format string, rsi/rdx/rcx/r8/r9 = arguments
; This is a simplified version - real printf is thousands of lines
mini_printf:
push rbp
mov rbp, rsp
push rbx
push r12
push r13
mov rbx, rdi ; rbx = format string pointer
mov r12, rsi ; r12 = first argument
; (Only this one argument is ever used: a second %d prints the same
; value again. A real implementation saves every argument register
; and walks them, which is what va_list does in C.)
.scan_loop:
movzx eax, byte [rbx] ; Load next character
test al, al ; Null terminator?
jz .done
cmp al, '%' ; Format specifier?
je .format
; Regular character - write it directly
lea rsi, [rbx] ; Buffer = current position
mov rax, 1 ; syscall: write
mov rdi, 1 ; fd: stdout
mov rdx, 1 ; count: 1 byte
syscall
inc rbx ; Advance format string
jmp .scan_loop
.format:
inc rbx ; Skip the '%'
movzx eax, byte [rbx] ; Load the specifier
cmp al, 'd'
je .print_decimal
cmp al, 's'
je .print_str
; Unknown specifier - skip it without printing anything
; (a format ending in a lone '%' would skip the terminator too)
inc rbx
jmp .scan_loop
.print_decimal:
mov rdi, r12 ; Pass the argument
call print_int
inc rbx
jmp .scan_loop
.print_str:
mov rdi, r12 ; Pass the string argument
call print_string
inc rbx
jmp .scan_loop
.done:
pop r13
pop r12
pop rbx
pop rbp
ret

Putting It Together

To run it, start a file called mini_printf.asm with this entry point, which prints a positive and a negative number, then paste strlen, print_string, print_uint, print_int and mini_printf after it. They land in the .text section that _start opens, and print_int switches to .data for its minus sign and back again:

asm
section .data
fmt: db "value: %d", 10, 0 ; 10 is the newline, 0 terminates the string
section .text
global _start
_start:
lea rdi, [rel fmt]
mov rsi, 12345
call mini_printf
lea rdi, [rel fmt]
mov rsi, -7
call mini_printf
mov rax, 60 ; syscall: exit
xor edi, edi ; exit code: 0
syscall

A two-rule Makefile builds it (the command lines must start with a tab):

makefile
mini_printf: mini_printf.o
ld -o $@ $<
mini_printf.o: mini_printf.asm
nasm -f elf64 -o $@ $<

Then make && ./mini_printf should print value: 12345 and value: -7, each on its own line. That needs a Linux x86-64 machine (or a VM or container); the binary talks straight to the Linux kernel, so it won't run on macOS or Windows directly.

What Real printf Does That We Skipped

Our mini printf clocks in around 80 lines. Glibc's printf is over 2,000 lines of C — many thousands of assembly instructions — and handles:

  • Width and precision specifiers (%10.2f)
  • All integer formats (%d, %u, %x, %o, %ld, %lld)
  • Floating-point formatting (%f, %e, %g)
  • Padding and alignment (%-20s, %05d)
  • The %n specifier (writing the number of characters printed so far)
  • Thread safety and locale support
  • Buffered I/O (accumulating characters and flushing in bulk)

The buffering is what makes real printf fast. Our version calls write per character, eating a kernel transition each time. Glibc collects output in a buffer sized from the file's preferred block size (typically 4 KB when stdout is a file or pipe) and flushes it in one go, or at each newline when stdout is a terminal. For bulk output that's thousands of times fewer syscalls.

You can feel the shape of all this without an assembler. The runner below is mini_printf translated back into C, still using nothing but write, with a va_list so it can walk past the first argument, and a counter that tallies every syscall it makes.

Try itAdd %c and %x. For %x, reuse print_uint's loop with 16 in place of 10 and a digits string to index into.
C (GCC 9.2.0)

Before you add anything, predict the number on the last line: each literal character costs one write, each specifier one more, and a negative number two. Then imagine a log line printed a million times.

The Takeaway

Building printf from scratch in assembly teaches you a few things:

  1. Syscalls are the only way out. Every byte of output eventually passes through write(2). Everything else — printf, puts, cout — is layers of buffering and formatting stacked on top.

  2. Integer-to-string conversion is expensive. Division is one of the slowest instructions on modern CPUs. A 64-bit integer can need up to 20 divisions to spell out in decimal.

  3. Format string parsing is just a state machine. Hit a %, switch code paths. Each specifier dispatches to its own handler. Same shape as a lexer, basically.

  4. The C standard library earns its keep. What we built in 100+ lines of assembly (handling only %d and %s) is a sliver of what printf actually does. The formatting code, buffering, and locale support represent decades of accumulated engineering.