原理参考:http://blog.csdn.net/lycb_gz/article/details/8214961
http://blog.csdn.net/lycb_gz/article/details/8232684
http://zhidao.baidu.com/link?url=JMAyNYIcR7g6Sbx3WNpvT7A5FXAkgVjE6fTVj_FDg15wCB4Aa8IJhsBFL_RqRnN8Ik_eZij54dpP9pS54jrZn_
程序如下:
/*输入海明码,输出是否有错并纠正:无错,输出“the error bit:0th”;有错,提示错误位,并给出纠错后的码。*/
#include <stdio.h>
#include <stdlib.h>#include <math.h>
#include <windows.h> //window下Sleep()以毫秒为单位;linux下用unistd.h,sleep()以秒为单位。
struct bit{
char code;
struct bit * next;
};
void get_code(struct bit * head,int * N);
int main()
{
struct bit * head,* p;
int N,r,R,sum,i,j;
printf("\nWelcome!");
while(1){
head = (struct bit *)malloc(sizeof(struct bit));
head->next=NULL;
get_code(head,&N);
for(r=2;r<=16;r++){
if((pow(2,r-1) < N)&&(N <= (pow(2,r)-1)))
break;
}
if(r>16){
printf("your input is wrong,please check to input!");
continue ;
}
R=r;
r=0;
for(i=1;i<=R;i++){
sum=0;
//定位
p=head;
for(j=1;j<pow(2,i-1);j++)
p=p->next;
//求和
while(1){
//取值
for(j=1;j<=pow(2,i-1);j++){
if(p==NULL) break;
if(p->code=='1')
sum=sum+1;
p=p->next;
}
//跳过
for(j=1;j<=pow(2,i-1);j++){
if(p==NULL) break;
p=p->next;
}
if(p==NULL) break;
}
r=((sum%2)<<(i-1))+r;
}
if(r>N){
printf("It can not be corrected! Maybe the num of error bits is more than one.");
continue ;
}
printf("the error bit:%dth\nthe correct code: ",r);
p=head;
j=1;
while(p!=NULL){
if(j==r){
if(p->code=='0')
p->code='1';
else
p->code='0';
}
printf("%c",p->code);
p=p->next;
j++;
}
free(head);
}
return 0;
}
void get_code(struct bit * head,int * N)
{
char c;
struct bit * p1,*p2;
*N=0;
printf("\n\n********************\nUsage:\n\n10011<enter>\n\ninput your code: ");
p1=p2=head;
while((c=getchar())!='\n'){
if((c=='0')|(c=='1')){
p1=p2;
(*N)++;
p2->code=c;
p2=(struct bit *)malloc(sizeof(struct bit));
p1->next=p2;
}
}
p1->next=NULL;
free(p2);
}