Question

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?

Was it helpful?

Solution

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).

OTHER TIPS

That's the same %x. All char values are converted to int before being passed to sprintf (or any other function that takes variable number of parameters).

printf("%x\n", 'a');

prints 61

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top