C语言实现CRC
1循环冗余校验码(CRC)的基本原理是:
在数据M的后面添加供差错检验用的n位冗余码。
得到N位冗余码的方法:用二进制的模2运算进行2^n乘M的运算,得到的(k+n) 位的数除以收发双方事先商定的长度为(n+1)位的除数P,得到余数R。这个R就作为冗余码拼接在数据M的后面发送出去,这个冗余码称为帧检验序列(FCS)。
2计算过程

3算法流程

4代码实现
#include<stdio.h> /* 示例:m=101001(41),p=1101(13),fcs=1 */ int showTopDigit(int x, int len) { int y; y=x>>(len-1); return y; } int main() { int m, p; printf("input M(一个十进制整数):");//待校验的数 scanf("%d",&m); printf("input P(一个十进制整数):");//除数 scanf("%d",&p); int count1=0, p1=p; while((p1&0x80000000)==0) { p1=p1<<1; count1++; } int LEN_P=32-count1;//P的位数 int count2=0, m1=m; while((m1&0x80000000)==0) { m1=m1<<1; count2++; } int LEN_M=32-count2;//M的位数 count1=LEN_P-1; m=m<<count1;//m*2^(LEN_P-1) int LEN_CH_M=LEN_M+count1;//m*2^(LEN_P-1)的位数 /*模2除法*/ int count3=0, p2=0, y=0; count3=LEN_CH_M-LEN_P;//P向前移位的位数 while(count3!=0 && count3>0) { p2=p<<count3; m=m^p2; LEN_CH_M--; y=showTopDigit(m,LEN_CH_M); if(y==1) count3=LEN_CH_M-LEN_P; while(y==0) { m=m^0; LEN_CH_M--; y=showTopDigit(m,LEN_CH_M); count3=LEN_CH_M-LEN_P; } } int fcs=m^p;//冗余码 printf("FCS=%d",fcs); return 0; }
效果:


浙公网安备 33010602011771号