在x86程序集中打印十六进制值

Hug*_*ugo 4 printing x86 assembly hex

我需要创建一个将内存地址转换为字节字符串的例程.那个字符串将成为打印以空字符结尾的字符串(我已经能够制作)的函数的输入.例如,如果我有一个地址0x1bf9,我需要将文本"1bf9"打印到屏幕上.这本书尚未进入32位模式,但有点暗示我们也需要它.这是我到目前为止:

TABLE:
db "0123456789ABCDEF", 0

STRING:
db 0

hex_to_char:
    lea bx, TABLE
    mov ax, dx

    mov ah, al ;make al and ah equal so we can isolate each half of the byte
    shr ah, 4 ;ah now has the high nibble
    and al, 0x0F ;al now has the low nibble
    xlat ;lookup al's contents in our table
    xchg ah, al ;flip around the bytes so now we can get the higher nibble 
    xlat ;look up what we just flipped
    inc STRING
    mov [STRING], ah ;append the new character to a string of bytes
    inc STRING
    mov [STRING], al ;append the new character to the string of bytes

    ret
Run Code Online (Sandbox Code Playgroud)

lur*_*ker 5

这会尝试增加文字标签,这是不正确的.此外,您的STRING内存位置仅分配一个字节(字符)而不是更大的数字,以适应您想要的字符串大小.

STRING:
    db 0

    inc STRING   ;THIS WON'T WORK
    mov [STRING], ah ;append the new character to a string of bytes
    inc STRING   ;THIS WON'T WORK
    mov [STRING], al ;append the new character to the string of bytes
Run Code Online (Sandbox Code Playgroud)

中性注释:用于的字符表xlat不需要为零终止.

另外,我建议保存和恢复一些寄存器作为良好的编程习惯.这样,调用函数不需要担心寄存器"在其后面"被改变.最终,你可能想要这样的东西:

TABLE:
    db "0123456789ABCDEF", 0

hex_to_char:
    push ax
    push bx

    lea   bx, [TABLE]
    mov   ax, dx

    mov   ah, al            ;make al and ah equal so we can isolate each half of the byte
    shr   ah, 4             ;ah now has the high nibble
    and   al, 0x0F          ;al now has the low nibble
    xlat                    ;lookup al's contents in our table
    xchg  ah, al            ;flip around the bytes so now we can get the higher nibble 
    xlat                    ;look up what we just flipped

    lea   bx, [STRING]
    xchg  ah, al
    mov   [bx], ax          ;append the new character to the string of bytes

    pop bx
    pop ax
    ret

    section .bss

STRING:
    resb  50                ; reserve 50 bytes for the string
Run Code Online (Sandbox Code Playgroud)

如果你想让函数返回刚刚保存的字符,你可以跳过push/pop ax.