Friday 23 August 2013

56. HAMMIMG CODE

CODE:
import java.util.*;
class Hamming
{
static Scanner sc = new Scanner(System.in);
int data[];
int parity[];
int code[];
int a[];
static int n,i,p;
void input()
{
System.out.println("Enter the no.of data bits:");
n=sc.nextInt();
data=new int[n];
System.out.println("Enter the data bits:");
for(i=n-1;i>=0;i--)
{
data[i]=sc.nextInt();
}
if(n==2 || n==3 || n==4)
p=3;
if(n==5 || n==6 || n==7 || n==8 || n==9 || n==10 || n==11)
p=4;
System.out.println("\nNo.of parity bits required = "+p);
parity=new int[p];
code=new int[n+p];
a=new int[n+p];
} void calculate()
{
for(i=0;i<p;i++)
{  parity[i]=0;
}
int j=0; int d=0; int x=0;
for(i=0;i<n+p;i++)
{
if(i==(Math.pow(2,x)-1))
{
a[i]=parity[j];
j++;
x++;
}else
{
a[i]=data[d];
d++;
}}
for(i=0;i<n+p;i++)
{  code[i]=a[i];
}  if((code[0]+code[2]+code[4]+code[6])%2==0)
code[0]=0;
else
code[0]=1;
if((code[1]+code[2]+code[5]+code[6])%2==0)
code[1]=0;
else
code[1]=1;
if((code[3]+code[4]+code[5]+code[6])%2==0)
code[3]=0;
else
code[3]=1;
System.out.println("\nThe Hamming Code is :");
for(i=(n+p)-1;i>=0;i--)
{  System.out.print(code[i]);
}
System.out.println();
}  void errorcheck()
{
System.out.println("\nEnter the Corrupted Hamming Code:");
for(i=(n+p)-1;i>=0;i--)
{  code[i]=sc.nextInt();
}
System.out.println("\nThe Corrupted Hamming Code:");
for(i=(n+p)-1;i>=0;i--)
{  System.out.print(code[i]);
}
System.out.println();
parity[0]=code[0];
parity[1]=code[1];
parity[2]=code[3];
if((((code[2]+code[4]+code[6])%2==0 && parity[0]==0)||(((code[2]+code[4]+code[6])%2)!=0) && parity[0]==1))
  parity[0]=0;
else
  parity[0]=1;
if((((code[2]+code[5]+code[6])%2==0 && parity[1]==0)||(((code[2]+code[5]+code[6])%2)!=0) && parity[1]==1))
 parity[1]=0;
else
 parity[1]=1;
if((((code[4]+code[5]+code[6])%2==0 && parity[2]==0)||(((code[4]+code[5]+code[6])%2)!=0) && parity[2]==1 ))
 parity[2]=0;
else
 parity[2]=1;
int word=0;
for(i=2;i>=0;i--)
{   word=word+(parity[i]*(int)Math.pow(2,i));                                 
 }           if(word==0)
System.out.println("\nThe data code is correctly received");   
else
System.out.println("\nThe bit no. "+word+" is wrongly received");
 if(code[word-1]==0)
code[word-1]=1;
else
code[word-1]=0;
System.out.println("\nThe Corrected Hamming Code:");
for(i=(n+p)-1;i>=0;i--)
{  System.out.print(code[i]);
}  System.out.println();
}
public static void main(String arg[])
{  Hamming h=new Hamming();
h.input();
h.calculate();
h.errorcheck();
}
}
OUTPUT:
Enter the no.of data bits:
4
Enter the data bits:
1
0
1
1
No. of parity bits required = 3
The Hamming Code is :
1010101
Enter the Corrupted Hamming Code:
1
0
1
0
1
0
0
The Corrupted Hamming Code:
1010100
The bit no. 1 is wrongly received
The Corrected Hamming Code:
1010101


No comments:

Post a Comment