You are on page 1of 2

/* Hamming Code

Program to generate a hamming code for an input string and also to identify a si
ngle bit error
in a coded data
*/
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include<string.h>
void checkbits(int choice,char *code,char *error);
void main()
{
int i=0,j,k,err_pos=0;
char inp[7],code[12],error[4]={'0','0','0','0'};
clrscr();
printf("Enter the binary data [7 bits]:\n");
scanf("%s",&inp);
k=0;
for(i=3;i<=11;i++)
if((i!=4)&&(i!=8))
code[i]=inp[k++]; // input data stored at specific pos.
checkbits(1,code,error);
printf("The code is:\n");
for(i=1;i<12;i++)
printf("%c",code[i]);
printf("\nEnter the hamming code [11 bits]:\n");
for(i=1;i<12;i++)
scanf("%c",&code[i]);
checkbits(2,code,error);
for(i=3;i>=0;i--)
{
if(error[i]=='1')
err_pos+=pow(2,i);
}
if(err_pos==0)
printf("\nNo error in the data");
else printf("\nError is at pos : %d",err_pos);
getch();
}//end of main
void checkbits(int choice,char *code,char *error) //function to check the par
ity bits
{
int i,j,k,parity=0;
for(i=0;i<4;i++) //each iteration for a check bit
{
for(j=pow(2,i);j<=11;j+=pow(2,i+1))
{
for(k=1;k<=pow(2,i);k++)
{
if(choice==1)
{
if (((j+k-1)!=pow(2,i))&&(j+k-1<=11)&&(code[j+k-
1]=='1'))
parity++;
}
else
{
if((j+k-1<=11)&&(code[j+k-1]=='1'))
parity++;
}
}
}
if (choice==1)
{
if((parity%2)==0)
code[pow(2,i)]='0';
else code[pow(2,i)]='1';
}
else
{
if((parity%2)==0)
error[i]='0';
else error[i]='1';
}
parity=0;
}
}// end of program

/* Output

Enter the binary data [7 bits]:


1101001
The code is:
01101011001
Enter the hamming code [11 bits]:
01101111001
Error is at pos :6

You might also like