Check sum

in this program, i want read hexadecimal numbers from data.txt, and creating checksum.

http://en.wikipedia.org/wiki/.hex

I have a problem witch reading numbers from .txt and putting them to: char pole[50];

in data.txt are for example:
10010000214601360121470136007EFE09D21901

and when program end, on the screen will be:
10010000214601360121470136007EFE09D2190140

40 - is the checksum

program would reading numbers in period:
10
01
00
00
21 etc...

(sorry for my english)

#include <stdio.h>
#include <conio.h>

int main ()
{
char a,i,j;
char suc=0;
char pole[50];
int c;

FILE*read=fopen("data.txt","r");
while (fscanf(read,"%2X",&a))!=EOF)
{
for(i=1;i<=20;i++)
{
pole[i]=a;
suc+=(~a+1);
}
}
for (j=1;j<=20;j++)
printf("%X",pole[j]);
printf("\n checksum: %X",suc);
getch();
}
The data file you gave was not the exact .hex format, I didn't see the ':' as the first char of the line. Also, in the .hex file is the checksum at the end. So, this is why I have this hardcoded to 20 here, to match your example file not the .hex file format.

I tried to modify your code as little as possible. The issue with this is you need to handle the '\n' when reading the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <cstdio>
#include <cstdlib>
using namespace std;
int main () 
{
   char i(0),*pEnd,byte[3] = {0}; 
   unsigned char suc(0),pole[50];
   FILE*read=fopen("data.txt","r");
   while ((fscanf(read,"%c%c",&byte[0],&byte[1]))!=EOF) { 
       pole[i]=static_cast<unsigned char>(strtol(byte,&pEnd,16));
       suc+=(~pole[i++]+1); 
       // Not knowing your input file I am going to break
       // after reading 20
       if ( i == 20 )
         break;
   }
 
   for (i=0;i<20;i++)
      printf("%02x",pole[i]);
   printf("\n checksum: %02X\n",suc); 

   fclose(read);   
}
$ ./a.out
10010000214601360121470136007efe09d21901
 checksum: 40

I have another version that uses getline and strings. If the input file always has 40 chars per-line followed by a new-line, then use a getline and substr to work with the data. It would look like
1
2
3
4
5
6
7
8
9
while data to read
    getline(in,str);
    Do I have the correct amount of data?
        for the amount of data 
            convert two byte string to one byte char (using str.substr function)
            adjust accumulator for checksum
        Print out data and checksum
    Reset any values to zero
end while

thanks a lot.
Topic archived. No new replies allowed.