Format specifier for hex char in C

Daniel picture Daniel · Oct 3, 2012 · Viewed 22.5k times · Source

Is there a format specifier for sprintf in C that maps a char to hex in the same way that %x maps an int to hex?

Answer

Jerry Coffin picture Jerry Coffin · Oct 3, 2012

Yes and no.

Since sprintf takes a variable argument list, all arguments undergo default promotion before sprintf receives them. That means sprintf will never receive a char -- a char will always be promoted to int before sprintf receives it (and a short will as well).

Yes, since what sprintf is receiving will be an int, you can use %x to convert it to hex format, and it'll work the same whether that value started as a char, short, or int. If (as is often the case) you want to print 2 characters for each input, you can use %2.2x.

Beware one point though: if your char is signed, and you start with a negative value, the promotion to int will produce the same numerical value, which normally won't be the same bit pattern as the original char, so (for example) a char with the value -1 will normally print out as ffff if int is 16 bits, ffffffff if int is 32 bits, or ffffffffffffffff if int is 64 bits (assuming the typical 2's complement representation for signed integers).