home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / library / dos / crc / crc_c / crc2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1987-07-29  |  2.0 KB  |  92 lines

  1. /* compute crc's */
  2. /* crc-16 is based on the polynomial x^16+x^15+x^2+1 */
  3. /*  The data is assumed to be fed in from least to most significant bit */
  4. /* crc-ccitt is based on the polynomial x^16+x^12+x^5+1 */
  5. /*  The data is fed in from most to least significant bit */
  6. /* The prescription for determining the mask to use for a given polynomial
  7.     is as follows:
  8.         1.  Represent the polynomial by a 17-bit number
  9.         2.  Assume that the most and least significant bits are 1
  10.         3.  Place the right 16 bits into an integer
  11.         4.  Bit reverse if serial LSB's are sent first
  12. */
  13. /* Usage : crc2 [filename] */
  14.  
  15. #include    <stdio.h>
  16. #include    <stdlib.h>
  17. #include    <string.h>
  18.  
  19. #define        M16    0xA001        /* crc-16 mask */
  20. #define        MTT    0x1021        /* crc-ccitt mask */
  21.  
  22. /* function declarations */
  23. unsigned int updcrc(unsigned int,int,unsigned int);
  24. unsigned int updcrcr(unsigned int,int,unsigned int);
  25. void perr(char *);
  26.  
  27. /* variables */
  28. char filename[100];
  29. unsigned int crc16,crctt;
  30. int ch;
  31. unsigned long num;
  32. FILE *fp;
  33.  
  34. /* driver */
  35. main(argc,argv)
  36. int argc; char **argv;
  37. {
  38.     if(argc>2) perr("Usage:  crc2 [filename]");
  39.     if(argc==2) strcpy(filename,argv[1]);
  40.     else
  41.     {
  42.         printf("\nEnter filename:  "); gets(filename);
  43.     }
  44.     if((fp=fopen(filename,"rb"))==NULL) perr("Can't open file");
  45.     num=0L; crc16=crctt=0;
  46.     while((ch=fgetc(fp))!=EOF)
  47.     {
  48.         num++;
  49.         crc16=updcrcr(crc16,ch,M16);
  50.         crctt=updcrc(crctt,ch,MTT);
  51.     }
  52.     fclose(fp);
  53.     printf("\nNumber of bytes = %lu\nCRC16 = %04X\nCRCTT = %04X",
  54.         num,crc16,crctt);
  55. }
  56.  
  57. /* update crc */
  58. unsigned int updcrc(crc,c,mask)
  59. unsigned int crc,mask; int c;
  60. {
  61.     int i;
  62.     c<<=8;
  63.     for(i=0;i<8;i++)
  64.     {
  65.         if((crc ^ c) & 0x8000) crc=(crc<<1)^mask;
  66.         else crc<<=1;
  67.         c<<=1;
  68.     }
  69.     return crc;
  70. }
  71.  
  72. /* update crc reverse */
  73. unsigned int updcrcr(crc,c,mask)
  74. unsigned int crc,mask; int c;
  75. {
  76.     int i;
  77.     for(i=0;i<8;i++)
  78.     {
  79.         if((crc ^ c) & 1) crc=(crc>>1)^mask;
  80.         else crc>>=1;
  81.         c>>=1;
  82.     }
  83.     return crc;
  84. }
  85.  
  86. /* error abort */
  87. void perr(s)
  88. char *s;
  89. {
  90.     printf("\n%s",s); exit(1);
  91. }
  92.