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?
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
charvalues 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:Doing a bitwise “and” with
0xFFclears all but the bottom 8 bits; casting tounsigned intshouldn’t be necessary, but it guarantees that the argument is actually of the type expected byprintfwith a"%02X"format.You should also consult your implementation’s documentation regarding any non-standard behavior for type promotions and
printf.