C语言实现CRC算法实例改进

来源:互联网 发布:农村淘宝前景怎么样 编辑:程序博客网 时间:2024/05/30 02:52

/*  本程序实现CRC算法,编译环境为turbo C 2.0 */

    /*
        改进1:增加可输入序列长度,数据+多项式序列总长增至32位(unsigned long位长);
        改进2:增加了一些检验措施;
        改进3:直接得出校验码(和余数)。
        参考测试数据:
        1.M=10101010,G=111
        2.M=10101010,G=1
        3.M=10101010,G=011
        4.M=12345678,G=111
        5.M=10101010,G=ABC
    */


#include<stdio.h>
int main()
{
void seq_scanf(unsigned long *s,int *n);    /*序列输入函数申明*/
void crc(unsigned long M,unsigned long G,int mN,int gN);
unsigned long M=0,G=0;
int mN=0,gN=0;

printf("/n/n/nPlease input the data sequence:/n");         /*输入数据序列*/
seq_scanf(&M,&mN);
if(mN<1)
   {printf("/n/nThe data sequence's length is too short!");exit(1);}
printf("/nPlease input the generator polynomial sequence:/n");   /*输入多项式序列*/
seq_scanf(&G,&gN);
if(gN<=1)
   {printf("/n/nThe generator polynomial sequence's length is too short!");exit(1);}
crc(M,G,mN,gN);            /*求crc校验码*/
return 0;
}


void seq_scanf(unsigned long *s,int *n)
{
/*s存储输入序列(按位存储),n存储序列长度*/
char c;
while((c=getchar())!='/n')   /*检测到回车时退出*/
     {
      if(c<48||c>49)
        {printf("/nNot valid sequence,you must input the sequence with 0 and 1./n/n");
         exit(1);}           /*序列必须由0和1组成*/
      if(*s<1&&c==48)  continue;  /*当输入序列开头为0时,忽略*/
      if(*s<1) *s=c-48;      /*-48:由字符转位存储*/
      else  *s=*s*2+c-48;
      (*n)++;
     }
}
 
  
void crc(unsigned long M,unsigned long G,int mN,int gN)
{
/* M是数据项,G是生成多项式,皆为无符长整型,mN,gN分别为M,G的有效位长度*/
void result_printf(unsigned long s,int n);
unsigned long g,MASK=1;                   /*MASK的作用:确认生成多项式G该向右移多少位*/
int i;

g=G;                  
M<<=gN-1;
G<<=mN-1;
MASK<<=gN+mN-2;
for(M=M^G;M!=0;M=M^G)      /*for语句,模2除法的实现*/
{
  for(i=0;(M&MASK)!=MASK;MASK>>=1) i++; 
  G>>=i;
  if(g>G) break;           /*检验G是否已移至末尾,是则退出*/
}
printf("/nThe remainder is:"); 
result_printf(M,gN-1);          /* 求余数,即校验码*/
}


void result_printf(unsigned long s,int n)
{
/*输出数据s的存储单元中的后n位*/
 if(n!=1) result_printf(s/2,n-1);
 printf("%d",s%2);
}

原创粉丝点击