计算机类
CRC校验实用程序库
CRC的本质是模-2除法的余数,采用的除数不同,CRC的类型也就不一样。通常,CRC的除数用生成多项式来表示。最常用的CRC码的生成多项式如表1所示。 @@10A08800.GIF;表1.最常用的CRC码及生成多项式@@ 由于CRC在通讯和数据处理软件中经常采用,笔者在实际工作中对其算法进行了研究和比较,总结并编写了一个具有最高效率的CRC通用程序库。该程序采用查表法计算CRC,在速度上优于一般的直接模仿硬件的算法,可以应用于通讯和数据压缩程序。 通常的CRC算法在计算一个数据段的CRC值时,其CRC值是由求解每个数值的CRC值的和对CRC寄存器的值反复更新而得到的。这样,求解CRC的速度较慢。通过对CRC算法的研究,我们发现:一个8位数据加到16位累加器中去,只有累加器的高8位或低8位与数据相作用,其结果仅有256种可能的组合值。因而,我们可以用查表法来代替反复的运算,这也同样适用于CRC32的计算。本文所提供的程序库中,函数crchware是一般的16位CRC的算法;mk-crctbl用以在内存中建立一个CRC数值表;crcupdate用以查表并更新CRC累加器的值;crcrevhware和crcrevupdate是反序算法的两个函数;BuildCRCTable、CalculateBlockCRC32和UpdateCharac terCRC32用于CRC32的计算。 /* CRC.C——CRC程序库 */ #define CRCCCITT 0x1021 #define CCITT-REV 0x8408 #define CRC16 0x8005 #define CRC16-REV 0xA001 #define CRC32-POLYNOMIAL 0xEDB88320L /* 以上为CRC除数的定义 */ #define NIL 0 #define crcupdate(d,a,t)*(a)=(*(a)<<8)^(t)[(*(a)>>8)^(d)]; #define crcupdate16(d,a,t)*(a)=(*(a)>>8^(t)[(*(a)^(d))&0x00ff]) /* 以上两个宏可以代替函数crcupdate和crcrevupdate */ #include<stdio.h> #include<stdlib.h> #include<alloc.h> /* 函数crchware是传统的CRC算法,其返回值即CRC值 */ unsigned short crchware(data,genpoly,accum) unsigned short data;/* 输入的数据 */ unsigned short genpoly;/* CRC除数 */ unsigned short accum;/* CRC累加器值 */ { static int i; data<<=8; for(i=8;i>0;i--) { if((data^accum)&0x8000) accum=(accum<<1)^genpoly; else accum<<=1; data<<=1; } return (accum); } /* 函数mk-crctbl利用函数crchware建立内存中的CRC数值表 */ unsigned short *mk-crctbl(poly,crcfn); unsigned short poly;/* CRC除数--CRC生成多项式 */ unsigned short (*crcfn)();/* 指向CRC函数(例如crchware)的指针 */ { /* unsigned short */malloc(); */ unsigned short *crctp; int i; if((crctp=(unsigned short*)malloc(256*sizeof(unsigned)))==0) return 0; for(i=0;i<256;i++) crctp[i]=(*crcfn)(i,poly,0); return crctp; } /* 函数mk-crctbl的使用范例 */ if((crctblp=mk-crctbl(CRCCCITT,crchware))==NIL) { puts("insuff memory for CRC lookup table.\n"); return 1; */ /* 函数crcupdate用以用查表法计算CRC值并更新CRC累加器值 */ void crcupdate(data,accum,crctab) unsigned short data;/* 输入的数据 */ unsigned short *accum;/* 指向CRC累加器的指针 */ unsigned short *crctab;/* 指向内存中CRC表的指针 */ { static short comb-val; comb-val=(*accum>>8)^data; *accum=(*accum<<8)^crctab[comb-val]; } /* 函数crcrevhware是传统的CRC算法的反序算法,其返回值即CRC值 */ unsigned short crcrevhware(data,genpoly,accum) unsigned short data; unsigned short genpoly; unsigned short accum; { static int i; data<<=1; for(i=8;i>0;i--) { data>>=1; if((data^accum)&0x0001) accum=(accum>>1)^genpoly; else accum>>=1; } return accum; } /* 函数crcrevupdate用以用反序查表法计算CRC值并更新CRC累加器值 */ void crcrevupdate(data,accum,crcrevtab) unsigned short data; unsigned short *accum; | ||
进入论坛讨论区 |
相关热词搜索: