Printing Hexadecimal Digits with Assembly

BSchlinker picture BSchlinker · Oct 4, 2010 · Viewed 14k times · Source

I'm trying to learn NASM assembly, but I seem to be struggling with what seems to simply in high level languages.

All of the textbooks which I am using discuss using strings -- in fact, that seems to be one of their favorite things. Printing hello world, changing from uppercase to lowercase, etc.

However, I'm trying to understand how to increment and print hexadecimal digits in NASM assembly and don't know how to proceed. For instance, if I want to print #1 - n in Hex, how would I do so without the use of C libraries (which all references I have been able to find use)?

My main idea would be to have a variable in the .data section which I would continue to increment. But how do I extract the hexadecimal value from this location? I seem to need to convert it to a string first...?

Any advice or sample code would be appreciated.

Answer

Paul R picture Paul R · Oct 4, 2010

First write a simple routine which takes a nybble value (0..15) as input and outputs a hex character ('0'..'9','A'..'F').

Next write a routine which takes a byte value as input and then calls the above routine twice to output 2 hex characters, i.e. one for each nybble.

Finally, for an N byte integer you need a routine which calls this second routine N times, once for each byte.

You might find it helpful to express this in pseudo code or an HLL such as C first, then think about how to translate this into asm, e.g.

void print_nybble(uint8_t n)
{
    if (n < 10) // handle '0' .. '9'
        putchar(n + '0');
    else // handle 'A'..'F'
        putchar(n - 10 + 'A');
}

void print_byte(uint8_t n)
{
    print_nybble(n >> 4); // print hi nybble
    print_nybble(n & 15); // print lo nybble
}

print_int16(uint16_t n)
{
    print_byte(n >> 8); // print hi byte
    print_byte(n & 255); // print lo byte
}