Printing character from register

2019-08-10 10:39发布

问题:

I'm using the NASM assembler.

The value returned to the eax register is supposed to be a character, when I attempt to print the integer representation its a value that looks like a memory address. I was expecting the decimal representation of the letter. For example, if character 'a' was moved to eax I should see 97 being printed (the decimal representation of 'a'). But this is not the case.

section .data
             int_format db "%d", 0
;-----------------------------------------------------------

mov eax, dword[ebx + edx]
push eax
push dword int_format
call _printf   ;prints a strange number
add esp, 8

xor eax, eax
mov eax, dword[ebx + edx]
push eax
call _putchar ;prints the correct character!
add esp, 4

So what gives here? ultimately I want to compare the character so it is important that eax gets the correct decimal representation of the character.

回答1:

mov eax, dword[ebx + edx]

You are loading a dword (32 bits) from the address pointed to ebx+edx. If you want a single character, you need to load a byte. For that, you can use movzx instruction:

movzx eax, byte[ebx + edx]

This will load a single byte to the low byte of eax (i.e. al) and zero out the rest of the register.

Another option would be to mask out the extra bytes after loading the dword, e.g.:

and eax, 0ffh

or

movxz eax, al

As for putchar, it works because it interprets the passed value as char, i.e. it ignores the high three bytes present in the register and considers only the low byte.