I have this code as given below for error checking by using hamming codes. I went through the algorithm on Wikipedia and also understood its working as described in the thread How does the Hamming code work?
But the code below uses some kind of sum of the parity bits in order to detect which bit is the error.
Can someone please explain how exactly the sum can be used to detect the error bit?
code:
#include<stdio.h>
#include<math.h>
void main()
{
int i,a[4],c[3],r[7],clk[3],n,sum=0;
printf("Enter data bits\n");
for(i=3;i>=0;i--)
scanf("%d",&a[i]);
printf("\n");
c[0]=(a[0]+a[1]+a[2])%2;
c[1]=(a[1]+a[2]+a[3])%2;
c[2]=(a[1]+a[0]+a[3])%2;
printf("data bits after hamming code is\n");
for(i=3;i>=0;i--)
printf("%d",a[i]);
for(i=2;i>=0;i--)
printf("%d",c[i]);
printf("Enter recieved code\n");
for(i=0;i<7;i++)
scanf("%d",&r[i]);
clk[0]=(r[3]+r[1]+r[2]+r[6])%2;
clk[1]=(r[0]+r[2]+r[1]+r[5])%2;
clk[2]=(r[0]+r[2]+r[3]+r[4])%2;
sum=4*clk[2]+2*clk[1]+1*clk[0];
if(sum==0)
printf("\n u have recived coorrect code\n");
if(sum==1)
{ printf("Error in check bit 2\n");
printf("The correct code is");
r[6]=(r[6]+1)%2;
for(i=0;i<7;i++)
printf("%d",r[i]);
}
if(sum==2)
{
printf("Error in check bit 1\n");
printf("The correct code is");
r[5]=(r[5]+1)%2;
for(i=0;i<7;i++)
printf("%d",r[i]);
}
if(sum==3)
{
printf("\nError in data bit 1");
printf("The correct code is");
r[1]=(r[1]+1)%2;
for(i=0;i<7;i++)
printf("%d",r[i]);
}
if(sum==4)
{
printf("\n Error in chect bit 0");
printf("The correct code is");
r[4]=(r[4]+1)%2;
for(i=0;i<7;i++)
printf("%d",r[i]);
}
if(sum==5)
{
printf("\n Error in data bits 3");
printf("The correct code is");
r[3]=(r[3]+1)%2;
for(i=0;i<7;i++)
printf("%d",r[i]);
}
if(sum==6)
{
printf("Error in data bits 0");
printf("The correct code");
r[0]=(r[0]+1)%2;
for(i=0;i<7;i++);
printf("%d",r[i]);
}
if(sum==7)
{
printf("Error in data bits 2");
printf("The correct code is");
r[2]=(r[2]+1)%2;
for(i=0;i<7;i++)
printf("%d",r[i]);
}
}
The bits are summed in such a way that each possible single-bit error produces a unique signature in
sum
. For example, all the odd-numbered bits are summed into bit zero, so if the error is in an odd-numbered bit, the signature will be odd. (Well, the numbering scheme in the example program jumbles the bits up, but that's the way I'd implement it and the way the Wikipedia article shows.)There is more than one Hamming code, so be sure to read the Wikipedia article on the Hamming (7,4) code.