How to print 1 byte with printf?

ahg8tOPk78 picture ahg8tOPk78 · Jan 13, 2017 · Viewed 77.5k times · Source

I know that when using %x with printf() we are printing 4 bytes (an int in hexadecimal) from the stack. But I would like to print only 1 byte. Is there a way to do this ?

Answer

Sourav Ghosh picture Sourav Ghosh · Jan 13, 2017

Assumption:You want to print the value of a variable of 1 byte width, i.e., char.

In case you have a char variable say, char x = 0; and want to print the value, use %hhx format specifier with printf().

Something like

 printf("%hhx", x);

Otherwise, due to default argument promotion, a statement like

  printf("%x", x);

would also be correct, as printf() will not read the sizeof(unsigned int) from stack, the value of x will be read based on it's type and the it will be promoted to the required type, anyway.