在装配中打印二进制字符串

时间:2018-01-11 05:39:50

标签: linux assembly printing x86-64

我正在编写一个程序来打印硬编码字的二进制字符串。以下是目前的情况:

main.asm

section .text
    global _start
    extern _print_binary_content

_start:
    push word [word_to_print] ; pushing word. Can we push just one byte?
    call _print_binary_content

    mov rax, 60
    mov rdi, 0
    syscall

section .data
    word_to_print: dw 0xAB0F

printer.asm

SYS_BRK_NUM equ 0x0C
BITS_IN_WORD equ 0x10
SYS_WRITE_NUM equ 0x01
STD_OUT_FD equ 0x01
FIRST_BIT_BIT_MASK equ 0x01
ASCII_NUMBER_OFFSET equ 0x30

section .text
    global _print_binary_content

_print_binary_content:
    pop rbp

    xor ecx, ecx ;zeroing rcx
    xor ebx, ebx ;zeroing rbx
    pop bx  ;the word to print the binary content of

    ;sys_brk for current location
    mov rax, SYS_BRK_NUM
    mov rdi, 0
    syscall
    ;end sys_brk

    mov r12, rax ;save the current brake location

    ;sys_brk for memory allocation 16 bytes
    lea rdi, [rax + BITS_IN_WORD]
    mov rax, SYS_BRK_NUM
    syscall
    ;end sys_brk

    xor ecx, ecx
    mov cl, byte BITS_IN_WORD - 1; used as a counter in the loop below

    loop:
        mov dx, bx
        and dx, FIRST_BIT_BIT_MASK
        add dx, ASCII_NUMBER_OFFSET
        mov [r12 + rcx], dl
        shr bx, 0x01
        dec cl
        cmp cl, 0
        jge loop

    mov rsi, r12
    mov rax, SYS_WRITE_NUM
    mov rdi, STD_OUT_FD
    mov rdx, BITS_IN_WORD
    syscall

    push rbp ; pushing return address back
    ret

如果我编译链接并运行此程序就可以了。但问题是关于性能以及编写汇编程序的惯例。在文件printer.asm中,我清理了ecx两次,这看起来并不是最佳的。也许有些寄存器不是用于它们的目的(我使用了intel-manual)。

你能帮助我改进这个非常简单的程序吗?

0 个答案:

没有答案