/* 本程序实现CRC算法,编译环境为turbo C 2.0 */ #include<stdio.h> int main() { void crc(unsigned long M,unsigned long G); unsigned long M,G; printf(\"Please put 2 sequences:\\n\"); scanf(\"%lu%lu\",&M,&G); printf(\"\\n\\nThe data is =%lu,the generator polynomial is =%lu\\n\\n\\n\",M,G); crc(M,G); return 0; }
void crc(unsigned long M,unsigned long G) { /* M是数据,G是生成多项式,皆为无符长整型*/ void trans2(unsigned long s,unsigned *t,int *n); void result_printf(unsigned s,int n); unsigned mD,gD,g; /*将输入的序列(10进制形式)用2进制mD,gD存储*/ int mN=0,gN=0; int MASK=1,i; trans2(M,&mD,&mN); trans2(G,&gD,&gN); g=gD; mD<<=gN-1; gD<<=mN-1; MASK<<=gN+mN-2; for(mD=mD^gD;mD!=0;mD=mD^gD) /*for语句,模2除法的实现*/ { for(i=0;(mD&MASK)!=MASK;MASK>>=1) i++; /*MASK的作用:确认生成多项式G该向右移多少位*/ gD>>=i; if(g>gD) break; } printf(\"The check is:\"); result_printf(mD,gN-1); }
void trans2(unsigned long s,unsigned *t,int *n) /*10进制格式转换成2进制存储, s为待转换数,t为转换结果,n为转换后的2进制位数*/ { if(s<10) *t=s; else { trans2(s/10,t,n); *t=(*t)*2+s%10; } (*n)++; } void result_printf(unsigned s,int n) { /*输出结果,即余数*/ if(n!=1) result_printf(s/2,n-1); printf(\"%d\",s%2); } |