Printing out hex values of a char* array in C gives odd values for binary input

c89, hex, printf

Solution

What you see is the result of sign extension from the `char` to `int`, using `unsigned char *` or casting to `unsigned char` before the cast to int is (implicitly?) performed should fix your problem.

Problem

Here's an odd problem that's been stumping me for a bit. The program is written in C89, and it reads a file into a char* array 16 bytes at a time (using fread and a size of sizeof(char)). The file is fopen'd with the "rb" flags. The array is then passed into a function that basically takes the 16 hex values and sticks it into a string, each value seperated by a space. Here's where the weirdness comes in. The function produces a nice hex dump, 16 bytes at a time, for a text file input that I have. But it screws up if I try it on a small bitmap image -- I end up with output in the string like ffffff88 instead of just 88. The hex values are placed into the output string using sprintf("%02x ", input[i]); in a loop. Why would this work properly for some files but not others?

Original source