19

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 ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
ahg8tOPk78
  • 317
  • 1
  • 2
  • 8

4 Answers4

25

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
10

You need to be careful how you do this to avoid any undefined behaviour.

The C standard allows you to cast the int to an unsigned char then print the byte you want using pointer arithmetic:

int main()
{
    int foo = 2;
    unsigned char* p = (unsigned char*)&foo;
    printf("%x", p[0]); // outputs the first byte of `foo`
    printf("%x", p[1]); // outputs the second byte of `foo`
}

Note that p[0] and p[1] are converted to the wider type (the int), prior to displaying the output.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    Nice. Suggest a separator though to not mash output together. Only corner problem is with rare `sizeof(int) == 1`. Maybe use `for (size_t i = 0; i< sizeof foo; i++) printf("%x\n", p[i]);` to print all bytes - even if there is only 1. – chux - Reinstate Monica Jan 13 '17 at 17:51
6

You can use the following solution to print one byte with printf:

unsigned char c = 255;
printf("Unsigned char: %hhu\n", c);
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
macario
  • 61
  • 1
  • 3
1

If you want to print a single byte that is present in a larger value type, you can mask and/or shift out the required value (e.g. int x = 0x12345678; x & 0x00FF0000 >> 16). Or just retrieve the required byte by casting the needed byte location using a (unsigned) char pointer and using an offset.

Ton Plooij
  • 2,583
  • 12
  • 15