crc-ccitt is based on the polynomial x^16+x^12+x^5+1

How to write a C Program crc-ccitt which based on the polynomial x^16+x^12+x^5+1 in C Programming Language ?

The prescription for determining the mask to use for a given polynomial is as follows:

                1.  Represent the polynomial by a 17-bit number
                2.  Assume that the most and least significant bits are 1
                3.  Place the right 16 bits into an integer

Solution:

  1. /* compute crc's */
  2. /* crc-ccitt is based on the polynomial x^16+x^12+x^5+1 */
  3. /* The prescription for determining the mask to use for a given polynomial
  4.         is as follows:
  5.                 1.  Represent the polynomial by a 17-bit number
  6.                 2.  Assume that the most and least significant bits are 1
  7.                 3.  Place the right 16 bits into an integer
  8. */
  9. #include        <stdio.h>
  10. #include        <stdlib.h>
  11. #include        <string.h>
  12. #include        <time.h>
  13. #define         MTT     0x1021          /* crc-ccitt mask */
  14. #define     CLK_TCK CLOCKS_PER_SEC
  15. /* function declarations */
  16. unsigned short int updcrc(unsigned short int,int,unsigned short int);
  17. void perr(char *);
  18. /* variables */
  19. char filename[100];
  20. unsigned short int crctt;
  21. int ch;
  22. unsigned long num;
  23. FILE *fp;
  24. /* driver */
  25. int main(argc,argv)
  26. int argc; char **argv;
  27. {
  28.  clock_t start,end;
  29.         if(argc>2) perr("Usage:  ccitt [filename]");
  30.         if(argc==2) strcpy(filename,argv[1]);
  31.         else
  32.         {
  33.                 printf("\nEnter filename:  ");
  34.                 gets(filename);
  35.         }
  36.         if((fp=fopen(filename,"rb"))==NULL) perr("Can't open file");
  37.         num=0L; crctt=0;
  38.         start=clock();
  39.        
  40.         while((ch=fgetc(fp))!=EOF)
  41.         {
  42.                 //if (ch == '\n')
  43.                 //      continue;
  44.                 num++;
  45.                 //int i; for (i=0;i<10000;i++){
  46.                 crctt=updcrc(crctt,ch,MTT);
  47.                 //}
  48.         }
  49.         end=clock();
  50.         fclose(fp);
  51.         printf("\nNumber of bytes = %lu\n CRCTT = %04X\n",      num,crctt);
  52.         printf("Czas trwania: %f\n",(double)(end-start)/CLK_TCK);
  53.         return 0;
  54. }
  55. /* update crc */
  56. unsigned short int updcrc(crc,c,mask)
  57. unsigned short int crc,mask; int c;
  58. {
  59.         int i;
  60.         c<<=8;
  61.         for(i=0;i<8;i++)
  62.         {
  63.                 if((crc ^ c) & 0x8000) crc=(crc<<1)^mask;
  64.                 else crc<<=1;
  65.                 c<<=1;
  66.         }
  67.         return crc;
  68. }
  69. /* error abort */
  70. void perr(s)
  71. char *s;
  72. {
  73.         printf("\n%s",s); exit(1);
  74. }


Learn More :