How to print a number in assembly NASM?

AR89 picture AR89 · Nov 19, 2011 · Viewed 35.6k times · Source

Suppose that I have an integer number in a register, how can I print it? Can you show a simple example code?

I already know how to print a string such as "hello, world".

I'm developing on Linux.

Answer

Martin picture Martin · Nov 19, 2011

If you're already on Linux, there's no need to do the conversion yourself. Just use printf instead:

;
; assemble and link with:
; nasm -f elf printf-test.asm && gcc -m32 -o printf-test printf-test.o
;
section .text
global main
extern printf

main:

  mov eax, 0xDEADBEEF
  push eax
  push message
  call printf
  add esp, 8
  ret

message db "Register = %08X", 10, 0

Note that printf uses the cdecl calling convention so we need to restore the stack pointer afterwards, i.e. add 4 bytes per parameter passed to the function.