1

Is there any reason to choose

printf("%hhx", foo);

over

printf("%x", foo);

Here foo is an unsigned char. I've conducted some tests and they appear to be interchangeable, is that really the case? If so, which one should use when bearing portability in mind?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Trey
  • 474
  • 2
  • 9
  • 32

1 Answers1

4

In the specific case of unsigned char foo, there isn't a difference. If you tried:

#include <stdio.h>

int main(void)
{
      signed char bar = '\xFF';
    unsigned char foo = '\xFF';
    printf("%hhx %x\n", bar, bar);
    printf("%hhx %x\n", foo, foo);
    return 0;
}

You'd typically get the output:

ff ffffffff
ff ff

The reason is that in both cases, the character is converted to an int when it is passed to printf(), but the signed character is converted to a negative int, which is then processed by conversion to unsigned char when the length modifier is hh and is left at full size (4 bytes, I'm assuming) when the length modifier is omitted.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • isn't `hh` a type modifier though? – Trey Mar 01 '18 at 07:25
  • 1
    In the standard ([C11 §7.21.6.1 The `printf` function ¶4 — also ¶7](https://port70.net/~nsz/c/c11/n1570.html#7.21.6.1p4)), the qualifiers such as `hh` are specifically called _length modifiers._ – Jonathan Leffler Mar 01 '18 at 07:28