In C, what would be the right way to read the contents of a binary file and check the checksum?
Here is an example of the data I'm working with:
0A 01 17 D8 04 00 07 9A 1F 10 FF CF 7F FF FF FF
FF 7F 7F 7F FF 7F FF FF FF FF 7F 81 01 01 03 01
01 01 01 81 00 73 67 68 66 97 6C 76 64 64 6A 6B
6E 64 66 67 44 41 [17 7A]
and
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 44 44 [00 85]
The checksum (between square brackets) stores the sum of the previous 54 bytes as a 2-byte (big-endian) number.
This is what I used:
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *f = fopen(argv[1], "rb");
unsigned char data[512];
fread(data, 1, 512, f);
int i;
int sum = 0;
for (i = 0; i < 54; i++)
{
sum += data[i];
}
if ((sum >> 8) == data[54] &&
(sum & 0xFF) == data[55])
{
printf("Checksum is valid.\n");
}
else
{
printf("Checksum is invalid.\n");
}
system("pause");
}
char , . . ?
!