📄 crc_example.cpp
字号:
#include<stdio.h>
#include<string.h>
char* Generator(char* Mx,char* Gx);
void Verifier(char* Tx,char* Gx);
void Alter(char* Tx,int arg);
#define MAX 20
int main()
{
char Mx[MAX],Gx[MAX];
char Tx[MAX];
int arg,n,k;
arg=0;
printf("请输入您要传输的报文M(x)(由0或1组成的字符串):");
scanf("%s",Mx);
printf("请输入生成多项式G(x)(由0或1组成的字符串):");
scanf("%s",Gx);
strcpy(Tx, Generator(Mx,Gx));
printf("数据传输时的报文序列为:%s\n",Tx);
Verifier(Tx,Gx);
printf("*************************************************\n");
n=strlen(Mx);
k=strlen(Gx);
while(arg==0)
{
printf("请输入数据的出错位置(1-%d选择一位)",n+k-1);
scanf("%d",&arg);
if( (arg<1) || (arg>n+k-1) )
{
arg=0;
printf("请重新出入 !");
}
}
Alter(Tx,arg);
Verifier(Tx,Gx);
return 0;
}
char* Generator(char* Mx,char* Gx)
{
int n,t,k,i;
char *tempG,*tempM,*Tx;
tempG=new char[MAX];
tempM=new char[MAX];
Tx=new char[MAX];
// n=strlen(M);
k=strlen(Gx);
strcpy(tempM,Mx);
for(i=1;i<k;i++) //M(x)*x^(k-1)
strcat(tempM,"0");
strcpy(Tx,tempM);
while(tempM[0]!='\0' && tempM[0]=='0')
strcpy(tempM,&tempM[1]);
t=strlen(tempM);
// k=strlen(Gx);
while(k<=t)
{
//make the divation
strcpy(tempG,Gx);
for(i=0;i<t-k;i++)
strcat(tempG,"0");
for(i=0;i<t;i++)
if(tempM[i]==tempG[i])
tempM[i]='0';
else
tempM[i]='1';
while(tempM[0]!='\0' && tempM[0]=='0')
strcpy(tempM,&tempM[1]);
t=strlen(tempM);
}
n=strlen(Tx);
for(i=1;i<=t;i++)
if(Tx[n-i]==tempM[t-i])
Tx[n-i]='0';
else
Tx[n-i]='1';
delete tempM;
delete tempG;
return Tx;
}
void Verifier(char* Tx,char* Gx)
{
int m,n,i;
char* tempT,*tempG;
tempG=new char[MAX];
tempT=new char[MAX];
strcpy(tempT,Tx);
n=strlen(Gx);
while(tempT[0]!='\0' && tempT[0]=='0')
strcpy(tempT,&tempT[1]);
m=strlen(tempT);
while(n<=m)
{
//make the divation
strcpy(tempG,Gx);
for(i=0;i<m-n;i++)
strcat(tempG,"0");
for(i=0;i<m;i++)
if(tempT[i]==tempG[i])
tempT[i]='0';
else
tempT[i]='1';
while(tempT[0]!='\0' && tempT[0]=='0')
strcpy(tempT,&tempT[1]);
m=strlen(tempT);
}
if(tempT[0]=='\0')
printf("The data is right :)\n");
else
printf("The data is wrong :(\n");
delete tempT;
delete tempG;
return;
}
//将多项式的第arg位数据变反
void Alter(char* Tx,int arg)
{
if(Tx[arg-1]=='0')
Tx[arg-1]='1';
else
Tx[arg-1]='0';
return ;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -