Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex file reading in C, some data corrupted?

Tags:

c

Iam having a problem with my school project. When i try to read in C program some hex data from a binary file i get some data filled with F's like this

00 64 61 56 03 00 00 00 09 00 00 00 73 00 00 00 
6A 69 75 FFFFFFE8 FFFFFFD1 5B FFFFFF8C FFFFFF93 73 FFFFFFAF 19 FFFFFF87 FFFFFFC1 4D FFFFFFFD FFFFFF93 
FFFFFFDF FFFFFFBE FFFFFFA0 09 FFFFFFBE FFFFFFD4 FFFFFFEB FFFFFFDE FFFFFFD3 FFFFFFF9 FFFFFFBD FFFFFFE6 FFFFFFFA FFFFFFAA 7E 29 
FFFFFFD3 FFFFFFE2 13 FFFFFFA5 3F FFFFFFA0 3A FFFFFFB2 50 53 3B 12 FFFFFFA1 39 FFFFFFA6 FFFFFF82 
FFFFFFF7 

While the original file in hexdump looks like this:

0000000 6400 5661 0003 0000 0009 0000 0073 0000
0000010 696a e875 5bd1 938c af73 8719 4dc1 93fd
0000020 bedf 09a0 d4be deeb f9d3 e6bd aafa 297e
0000030 e2d3 a513 a03f b23a 5350 123b 39a1 82a6
0000040 00f7

Iam not quiet sure, why is this happening.

I tested it using this code:

int main()
{
   char ch, file_name[25];
   FILE *fp;

   printf("Enter the name of file you wish to see\n");
   fgets(file_name, sizeof(file_name), stdin);
   file_name[strlen(file_name)-1] = 0x00;

   fp = fopen(file_name,"rb"); // read binary mode

   if( fp == NULL ) //error checking
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }

   printf("The contents of %s file are :\n", file_name);

   int i;
   while( ( ch = fgetc(fp) ) != EOF )
   {
      printf("%02X ",ch);
      if( !(++i % 16) ) putc('\n', stdout);
   }
   fclose(fp);
   putc('\n', stdout);

   return 0;
}
like image 328
dewdew Avatar asked Dec 11 '25 03:12

dewdew


1 Answers

You just tripped on the sign extension done by the processor when expanding a signed integer value to a larger integer type:

The type char is only one byte wide, while the printf() function expects int arguments (four bytes on your system). Since char is signed on your system, the other 24 bits are filled with copies of the sign bit, producing the FFFFFF pattern that you see in your output. Note that your output is correct, except for the FFFFFF-prefixes to all bytes that start with a hex digit greater or equal to 8.

You can avoid this by simply declaring ch as unsigned char. That will be zero extended to an int, and your output will be correct.

like image 83
cmaster - reinstate monica Avatar answered Dec 13 '25 15:12

cmaster - reinstate monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!