海明码和CRC校验的C语言实现.doc
海明码和CRC校验的C语言实现
海明码
//code by zxf 2010.4.10
#include
#include
#include
//N代表待编码数据的上限位数
#define N 100
int HmLength(int k);//计算海明码校验位位数
void InCode(char *data,char *c,int k,int r);//计算海明码每个校验位的数值
void main()
{
int k=0,r=0,dnum=0,cnum=0;
char data[N];
char c[N];
clrscr();
printf("Now please input the data you want to Incode:");
for(k=0;k
{
data[k]=getche();
if(data[k]!='0'&&data[k]!='1')
{
break;
}
}
printf("\n__________________________________________________________\n");
r=HmLength(k);//求取校验位数
printf("k=%d r=%d The length of Hamming code=%d\n",k,r,r+k);//输出海明码相关位数信息
InCode(data,c,k,r);//计算海明码
printf("The Hamming code is:");
for(int j=1;j
{
if(j==(int)pow(2,cnum))
{
printf("%c",c[cnum]);
cnum++;
}
else
{
printf("%c",data[dnum]);
dnum++;
}
}
getch();
}
/*
*@func:计算校验码
*@param:data 待编码数据,c 校验码,k 数据长度,r 校验码位数
*code by zxf
*/
void InCode(char *data,char *c,int k,int r)
{
for(int i=0;i
{
int sum=0,dnum=0,cnum=0;
for(int j=1;j
{
if(j==(int)pow(2,cnum))//去掉矩阵的全零行
{
cnum++;//记录校验码循环位数
}
else
{
int x=0,y=0;
x=pow(2,i);
y=j%(x*2);
x=y/x;//通过取余取商计算获取矩阵第r-i列第j行元素的值
sum+=data[dnum]*x;//累加乘积
dnum++;//记录数据的循环位数
}
}
c[i]=sum%2==0?'0':'1';//通过结果的奇偶设置校验位的值
}
}
/*
*@func:计算校验码的位数
*@param: k 数据长度
*@return: 校验码位数
*code by zxf
*/
int HmLength(int k)
{
int r=0,flag=1;
while (flag!=0)//循环到2^r-1>=r+K时即得到校验码的位数
{
int temp=0;
temp=pow(2,r);
temp=temp-1;
flag=(temp-r-k<0);
r++;
}
return r-1;
}
程序演示:
计算 1100
计算 1000001
计算 10101010101010101010101010101010101010
CRC校验
//code by zxf 2010.4.10
#include
#include
#includ