According to the standard mention of the %x format specifier with fprintf()
o,u,x,X
The unsigned int argument is converted to unsigned octal code ( o ), unsigned decimal ( u ), or unsigned hexadecimal notation (x or X) in the dddd style; [...]
So, the expected type of the argument %x is unsigned int .
Now that printf() is a variational function, only the default distribution rule is applied to its arguments. In your code, chars is an array of type char (the signature of which is implementation dependent), in the case of
printf("%02x\n", chars[0]);
the value of chars[0] gets promoted to int , which is not the expected type for %x . Therefore, the output is incorrect, since int and unsigned int are not the same type. [Cm. Β§6.7.2, C11 ]. So without explicit casting
printf("%02x\n", (unsigned int)chars[0]);
it causes undefined behavior .
FWIW, if you have a supported C99 compiler, you can use the hh length modifier to get around this, for example
printf("%02hhx\n", (unsigned char)chars[0]);
Sourav ghosh
source share