Search code examples
linuxassemblyx86nasm

How to print a number in assembly NASM?


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.


Solution

  • 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.