在Assembly x86中将字符打印到标准输出

use*_*758 5 printing x86 assembly

关于如何使用Assembly将字符打印到屏幕上我有点困惑.该架构是x86(linux).可以调用其中一个C函数还是有更简单的方法?我想输出的字符存储在寄存器中.

谢谢!

qwr*_*qwr 7

为了完整起见,这里是如何在没有 C 的情况下做到这一点。

使用 DOS 中断

AH = 02h - 将字符写入标准输出

中写入字符DL。我自己没有测试过这个。在 NASM 语法中类似

mov ah, 02h
int 21h
Run Code Online (Sandbox Code Playgroud)

x86-32 Linuxwrite系统调用

write需要字符串的地址。我所知道的最简单的方法是将您的角色推入堆栈。

push    $0x21       # '!'
mov     $4, %eax    # sys_write call number 
mov     $1, %ebx    # write to stdout (fd=1)
mov     %esp, %ecx  # use char on stack
mov     $1, %edx    # write 1 char
int     $0x80   
add     $4, %esp    # restore sp 
Run Code Online (Sandbox Code Playgroud)

注册订单信息

x86-64 Linuxwrite系统调用

与上面类似,但调用号现在是 1,syscall而不是int $0x80,并且调用约定寄存器不同。

push    $0x21       # '!'
mov     $1, %rax    # sys_write call number 
mov     $1, %rdi    # write to stdout (fd=1)
mov     %rsp, %rsi  # use char on stack
mov     $1, %rdx    # write 1 char
syscall   
add     $8, %rsp    # restore sp 
Run Code Online (Sandbox Code Playgroud)


Mar*_*tin 5

当然,您可以使用任何正常的C函数.这是一个使用printf打印输出的NASM示例:

;
; 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
Run Code Online (Sandbox Code Playgroud)

如果您只想打印单个字符,可以使用putchar:

push eax
call putchar
Run Code Online (Sandbox Code Playgroud)

如果你想打印一个数字,你可以这样做:

mov ebx, 8
push ebx
push message
call printf
...    
message db 'The number is: %d', 10, 0
Run Code Online (Sandbox Code Playgroud)