Alex Rivera | Logout

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

Asked 2012-09-10T02:42:48.533
24

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?

Edit
Report

1 Answer

8

you are sending a char to a format string which expects an int. The printf function is grabbing another byte off the stack to fill it out. Try

 printf("%02X",(int)(status|0xC0));
answered 2012-09-10T02:49:15.367

Your Answer