Printing a character to standard output in Assembly x86

Question!

I'm a little confused about how to print a character to the screen using Assembly. The architecture is x86 (linux). Is it possible to call one of the C functions or is there a simpler way? The character I want to output is stored in a register.

Thanks!



Answers

Calling putchar(3) is the simplest way. Just move the char's value into the rdi register (for x86-64, or edi for x86), and call putchar.

E.g. (for x86-64):

asm("movl $120, %rdi\n\t"
    "call putchar\n\t");

will print an x to stdout.



Sure, you can use any normal C function. Here's a NASM example that uses printf to print some output:

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

extern printf   ; If you need other functions, list them in a similar way

global main

main:

    mov eax, 0x21  ; The '!' character
    push eax
    push message
    call printf
    add esp, 8     ; Restore stack - 4 bytes for eax, and 4 bytes for 'message'
    ret

message db 'The character is: %c', 10, 0

If you only want to print a single character, you could use putchar:

push eax
call putchar

If you want to print out a number, you could do it like this:

mov ebx, 8
push ebx
push message
call printf
...    
message db 'The number is: %d', 10, 0
By : Martin


This video can help you solving your question :)
By: admin