Monday, November 16, 2009

Write a program to generate hamming code

Write a program to generate hamming code.

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
void main()
{ clrscr();
char code1[15];
int i,j,d=0,p,l,a[8];
unsigned long int c,num=0;
cout<<"\n Enter a binary code(max 10 bits):";
gets(code1);
for(i=0;i<strlen(code1);i++)
{ switch(code1[i])
{ case '0':
case '1': break;
default: cout<<"\n Not a binary number.\n ABORTING!!!!";
getch();
exit(1);
}
}
cout<<"\n The length of the binary code : "<<l<<"\n";
for(i=0;i<5;i++)
{
if(l+1+i<=pow(2,i))
break;
}
p=i;
char code3[20];
int l1=l+p;
char e='p',f='q',g='r',h='s';
for(i=0,j=0;i<l1;i++)
{ switch(i+1)
{
case 1: code3[i]=e;
break;
case 2: code3[i]=f;
break;
case 4: code3[i]=g;
break;
case 8: code3[i]=h;
break;

default: code3[i]=code1[j];
j++;
break;
};
}
cout<<"\n\n The new code : \n";
for(i=0;i<l1;i++)
{ if(i<10)
cout<<code3[i]<<" ";
else
cout<<" "<<code3[i]<<" ";
}
cout<<"\n";
for(i=0;i<l1;i++)
cout<<i+1<<" ";
cout<<"\n";
int c1=0,c2=0,c3=0,c4=0;
for(i=0;i<l1;i++)
{ switch(i+1)
{ case 1:
case 3:
case 5:
case 7:
case 9:
case 11: if(code3[i]=='1')
{ c1++;
}
break;
};
switch(i+1)
{ case 2:
case 3:
case 6:
case 7:
case 10:
case 11: if(code3[i]=='1')
{ c2++;
}
break;
};
switch(i+1)
{ case 4:
case 5:
case 6:
case 7:
case 12: if(code3[i]=='1')
c3++;
break; };
switch(i+1)
{ case 8:
case 9:
case 10:
case 11: if(code3[i]=='1')
{ c4++; }
break;
};
}
if(c1%2!=0)
{ e='1';
}
else
{ e='0'; }
if(c2%2!=0)
{ f='1'; }
else
{ f='0';
}
if(c3%2!=0)
{ g='1'; }
else
{ g='0'; }
if(c4%2!=0)
{ h='1';
}
else
{ h='0';
}
for(i=0,j=0;i<l1;i++)
{ switch(i+1)
{
case 1: code3[i]=e;
break;
case 2: code3[i]=f;
break;
case 4: code3[i]=g;
break;
case 8: code3[i]=h;
break;
default: code3[i]=code1[j];
j++;
break;
}
}
cout<<"\n\n The Hamming Code : \n";
for(i=0;i<l1;i++)
cout<<code3[i]<<" ";
getch();
}





OUTPUT:
Enter a binary code(max 10 bits):111111111
Entered binary number :
111111111
The new length of the code : 13
The new code :
p q 1 r 1 1 1 s 1 1 1 1 1
1 2 3 4 5 6 7 8 9 10 11 12 13
The Hamming Code :
1 1 1 0 1 1 1 1 1 1 1 1 1