pixel_data is a vector of char.
When I do printf(" 0x%1x ", pixel_data[0] ) I’m expecting to see 0xf5.
But I get 0xfffffff5 as though I was printing out a 4 byte integer instead of 1 byte.
Why is this? I have given printf a char to print out – it’s only 1 byte, so why is printf printing 4?
NB. the printf implementation is wrapped up inside a third party API but just wondering if this is a feature of standard printf?
You’re probably getting a benign form of undefined behaviour because the
%xmodifier expects anunsigned intparameter and acharwill usually be promoted to anintwhen passed to a varargs function.You should explicitly cast the char to an
unsigned intto get predictable results:Note that a field width of one is not very useful. It merely specifies the minimum number of digits to display and at least one digit will be needed in any case.
If
charon your platform is signed then this conversion will convert negativecharvalues to largeunsigned intvalues (e.g.fffffff5). If you want to treat byte values as unsigned values and just zero extend when converting tounsigned intyou should useunsigned charforpixel_data, or cast viaunsigned charor use a masking operation after promotion.e.g.
or