- 1 year ago
How do I printf and scanf in x86_64 assembly?
In x86_64 assembly, the equivalent instructions for printf
and scanf
from the C programming language are printf
and scanf
respectively. However, these instructions are not available directly in assembly language. Instead, you need to call the corresponding functions from the C runtime library.
Here's an example of how you can use printf
and scanf
in x86_64 assembly code:
assemblysection .data
format db "Hello, World!", 0
input_format db "%d", 0
output_format db "You entered: %d", 0
input_buffer times 4 db 0
output_buffer times 4 db 0
section .text
global _start
_start:
; Call printf
mov rdi, format ; Format string address
xor eax, eax ; Clear EAX register
call printf
; Call scanf
mov rdi, input_format ; Input format string address
mov rsi, input_buffer ; Input buffer address
xor eax, eax ; Clear EAX register
call scanf
; Call printf
mov rdi, output_format ; Output format string address
mov rsi, [input_buffer] ; Value to print from input buffer
xor eax, eax ; Clear EAX register
call printf
; Exit program
xor edi, edi ; Clear EDI register
mov eax, 60 ; System call number for exit
syscall
section .data
format db "Hello, World!", 0
input_format db "%d", 0
output_format db "You entered: %d", 0
input_buffer times 4 db 0
output_buffer times 4 db 0
section .text
global _start
_start:
; Call printf
mov rdi, format ; Format string address
xor eax, eax ; Clear EAX register
call printf
; Call scanf
mov rdi, input_format ; Input format string address
mov rsi, input_buffer ; Input buffer address
xor eax, eax ; Clear EAX register
call scanf
; Call printf
mov rdi, output_format ; Output format string address
mov rsi, [input_buffer] ; Value to print from input buffer
xor eax, eax ; Clear EAX register
call printf
; Exit program
xor edi, edi ; Clear EDI register
mov eax, 60 ; System call number for exit
syscall
In the above example, the code uses the printf
function to print "Hello, World!" and the scanf
function to read an integer from the user. Then, it uses printf
again to display the entered value.
To assemble and run this code, you will need to use an x86_64 assembler, such as NASM, and link it with the C runtime library.
Please note that the exact method of calling these functions and passing arguments may vary depending on the assembly language and the specific assembler you are using. Consult the documentation for your specific assembler and C runtime library for detailed instructions on how to use printf
and scanf
in your assembly code.