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:
- /* compute crc's */
- /* crc-ccitt is based on the polynomial x^16+x^12+x^5+1 */
- /* 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
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #define MTT 0x1021 /* crc-ccitt mask */
- #define CLK_TCK CLOCKS_PER_SEC
- /* function declarations */
- unsigned short int updcrc(unsigned short int,int,unsigned short int);
- void perr(char *);
- /* variables */
- char filename[100];
- unsigned short int crctt;
- int ch;
- unsigned long num;
- FILE *fp;
- /* driver */
- int main(argc,argv)
- int argc; char **argv;
- {
- clock_t start,end;
- if(argc>2) perr("Usage: ccitt [filename]");
- if(argc==2) strcpy(filename,argv[1]);
- else
- {
- printf("\nEnter filename: ");
- gets(filename);
- }
- if((fp=fopen(filename,"rb"))==NULL) perr("Can't open file");
- num=0L; crctt=0;
- start=clock();
- while((ch=fgetc(fp))!=EOF)
- {
- //if (ch == '\n')
- // continue;
- num++;
- //int i; for (i=0;i<10000;i++){
- crctt=updcrc(crctt,ch,MTT);
- //}
- }
- end=clock();
- fclose(fp);
- printf("\nNumber of bytes = %lu\n CRCTT = %04X\n", num,crctt);
- printf("Czas trwania: %f\n",(double)(end-start)/CLK_TCK);
- return 0;
- }
- /* update crc */
- unsigned short int updcrc(crc,c,mask)
- unsigned short int crc,mask; int c;
- {
- int i;
- c<<=8;
- for(i=0;i<8;i++)
- {
- if((crc ^ c) & 0x8000) crc=(crc<<1)^mask;
- else crc<<=1;
- c<<=1;
- }
- return crc;
- }
- /* error abort */
- void perr(s)
- char *s;
- {
- printf("\n%s",s); exit(1);
- }