Home >Backend Development >C++ >Why Does `printf` Show Unexpected Output When Printing Hexadecimal Bytes from a Char Vector?
When working with a vector of chars (pixel_data), printing a single byte as a hexadecimal value (printf(" 0x%1x ", pixel_data[0])) may unexpectedly produce a four-byte integer (0xfffffff5) instead of the intended value (0xf5).
Printf typically expects an unsigned integer parameter for the %x modifier. However, a char is promoted to an int when passed to a varargs function like printf. This promotion results in the printing of additional bytes.
To ensure predictable results, explicitly cast the char to an unsigned int:
printf(" 0x%1x ", (unsigned)pixel_data[0]);
printf(" 0x%x ", (unsigned)(unsigned char)pixel_data[0]);
printf(" 0x%x ", (unsigned)pixel_data[0] & 0xffU);
The %1x field width specifies the minimum number of digits to display. However, it has limited usefulness in this context as at least one digit is always needed.
The above is the detailed content of Why Does `printf` Show Unexpected Output When Printing Hexadecimal Bytes from a Char Vector?. For more information, please follow other related articles on the PHP Chinese website!