How to print unsigned char as 2-digit hex value in C?

Asad Waheed picture Asad Waheed · Sep 10, 2012 · Viewed 64.6k times · Source

I am trying to printout an unsigned char value as a 2-Digit hex value, but always getting the result as 4-Digit hex values, not sure what's wrong with my code.

// unsigned char declaration
unsigned char status = 0x00;
// printing out the value 
printf("status = (0x%02X)\n\r", (status |= 0xC0));

I am expecting a 2 digit hex result as 0xC0, but I always get 0xC0FF.

As well, when I tried to print the same variable (status) as an unsigned char with the %bu format identifier I got the output as 255.

How do you get just the two hex characters as output?

Answer

Keith Thompson picture Keith Thompson · Sep 10, 2012

As far as I know, the Keil C compiler doesn't fully conform to the C standard. If so, it's likely that it doesn't quite follow the standard promotion rules for things like passing char values to variadic functions; on an 8-bit CPU, there are performance advantages in not automatically expanding 8-bit values to 16 bits or more.

As a workaround, you can explicitly truncate the high-order bits before passing the argument to printf. Try this:

#include <stdio.h>

int main(void) {
    unsigned char status = 0x00;
    status |= 0xC0;

    printf("status = 0x%02X\n", (unsigned int)(status & 0xFF));
    return 0;
}

Doing a bitwise "and" with 0xFF clears all but the bottom 8 bits; casting to unsigned int shouldn't be necessary, but it guarantees that the argument is actually of the type expected by printf with a "%02X" format.

You should also consult your implementation's documentation regarding any non-standard behavior for type promotions and printf.