Print hex values ​​in x86 assembly

I need to make a procedure that converts a memory address into a string of bytes. Then this line will be the input for a function that prints lines with zero completion (which I could already do). For example, if I have the address 0x1bf9, I need to print the text "1bf9" on the screen. The book has not yet switched to 32-bit mode, but this is a hint that we will also need this. This is what I have so far:

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 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 
+4
source share
2 answers

This is an attempt to increase the letter mark, which is incorrect. Also, your location in STRING allocates only one byte (char) instead of a larger number to accommodate the size of the line that you intend.

 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 

Neutral Comment: The character table used for xlat should not be zero terminated.

I would also recommend saving and restoring some registers as a good asm programming practice. Thus, the calling function does not need to worry about the registers changing β€œbehind”. Ultimately, you probably want something like this:

 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 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 

If you want the function to return the character that it just saved, you can skip push / pop ax .

+4
source

Please take a look at my answer on this page to convert a 32-bit value in EAX to 8 hexadecimal ASCII bytes: Printing a number in assembler?

0
source

Source: https://habr.com/ru/post/1502881/


All Articles