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

时间:2013-09-18 18:28:52

标签: assembly printing x86 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

3 个答案:

答案 0 :(得分: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

中性评论:用于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

如果您希望该函数返回刚刚保存的字符,您可以跳过ax的推/弹。

答案 1 :(得分:0)

请查看我在此页面上的答案,以便将EAX中的32位值转换为8个十六进制ASCII字节:Printing out a number in assembly language?

答案 2 :(得分:0)

如果用未记录的“ AAM 10h”(D4 10)替换字节分割,则可以进一步优化此大小。