Guest User

NMEA checksum checker

a guest
Feb 28th, 2015
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int hextoint(char c)
  4. {
  5.   if((c>='0')&&(c<='9'))
  6.     return c-'0';
  7.   if((c>='A')&&(c<='F'))
  8.     return c-'A'+10;
  9.   if((c>='a')&&(c<='f'))
  10.     return c-'a'+10;
  11.   return -1;
  12. }
  13.  
  14. int main(int argc,char **argv)
  15. {
  16.   if(argc!=2)
  17.   {
  18.     fprintf(stderr,"%s needs exactly 1 argument\n",argv[0]);
  19.     return -1;
  20.   }
  21.  
  22.   char *nmea=argv[1];
  23.   if(*nmea++!='$')
  24.   {
  25.     fprintf(stderr,"NMEA doesn't begin with '$' %s\n",argv[1]);
  26.     return 2;
  27.   }
  28.  
  29.   int csum=0;
  30.   while((*nmea)&&(*nmea!='*'))
  31.     csum^=*nmea++;
  32.  
  33.   if(!*nmea)
  34.   {
  35.     fprintf(stderr,"NMEA doesn't contain '*' %s\n",argv[1]);
  36.     return 3;
  37.   }
  38.  
  39.   ++nmea;
  40.   if((!nmea[0])||(!nmea[1]))
  41.   {
  42.     fprintf(stderr,"Checksum missing from the end: %s\n",argv[1]);
  43.     return 4;
  44.   }
  45.   int tmp=hextoint(nmea[0]);
  46.   int checksum=hextoint(nmea[1]);
  47.   if((tmp==-1)||(checksum==-1))
  48.   {
  49.     fprintf(stderr,"Invalid hex digit: %s\n",argv[1]);
  50.     return 5;
  51.   }
  52.  
  53.   checksum+=tmp<<4;
  54.   if(csum!=checksum)
  55.   {
  56.     fprintf(stderr,"Checksums are different: %02x!=%02x %s\n",csum,checksum,argv[1]);
  57.     return 1;
  58.   }
  59.  
  60.   return 0; // everything was OK
  61. }
Advertisement
Add Comment
Please, Sign In to add comment