校验位为位置
数据从低位开始传输
C语言代码如下:
#include"stdio.h"
#include"stdlib.h"
typedef struct hanming
{
int *H;
int *D;
int *HD;
int n;
int k;
}hanming;
int mypow(int a,int b)
{
int a1=a;
if(b==0)
{
return 1;
}
while(--b)
{
a=a*a1;
}
return a;
}
void init_hanming(hanming *Han,int n,int k)
{
int i=0;
Han->D=(int *)malloc((n)*sizeof(int));
Han->H=(int *)malloc((k)*sizeof(int));
Han->HD=(int *)malloc((n+k)*sizeof(int));
Han->n=n;
Han->k=k;
}
int count_1(int a) {
int count = 0;
while (a) {
a = a>>1;
count++;
}
return count;
}
int data_n(int data,int l)
{
int n=0;
for(l;l>=0;l--)
{
n=data%2;
data=data>>1;
}
return n;
}
int k_value(int n)
{
int count=0;
int k=0;
while(mypow(2,k)<n+k+1)
{
k++;
}
return k;
}
int Han_D(int data,hanming *Han)
{
int i=0;
for(i;i<Han->n;i++)
{
Han->D[i]=data_n(data,i);
// printf("D %d\n",Han->D[i]);
}
// printf("==========\n");
}
int Han_H(hanming *Han)
{
int i=0;
int j=0;
for(i;i<Han->k;i++)
{
Han->H[Han->k-i-1]=0;
for(j=0;j<Han->n;j++)
{
if(i!=j)
{
Han->H[Han->k-i-1]=Han->H[Han->k-i-1]^Han->D[j];
}
}
// printf("H %d\n",Han->H[Han->k-i-1]);
}
// printf("==============\n");
}
int Han_HD(hanming *Han)
{
int i=0;
int a=0,b=0,c=0;
int value=0;
for(i;i<Han->n+Han->k;i++)
{
if(i==(mypow(2,a)-1))
{
Han->HD[i]=Han->H[a];
value=value+Han->H[a]*mypow(2,c++);//反向计算十进制结果,方便正序输出
a++;
}else{
Han->HD[i]=Han->D[b];
value=value+Han->D[b]*mypow(2,c++);
b++;
}
// printf("HD %d\n",Han->HD[i]);
}
return value;
}
void printfs(int num)
{
while(num>0)
{
printf("%d",num%2);
num=num>>1;
}
printf("\n");
}
int main()
{
int data=0B1100;
int n=count_1(data);
int k=k_value(n);
int value=0B0;
hanming Han;
init_hanming(&Han,n,k);
Han_D(data,&Han);
Han_H(&Han);
value=Han_HD(&Han);
// printf("%d\n",value);
printfs(value);
return 0;
}