-
Notifications
You must be signed in to change notification settings - Fork 2
/
HammingCode.java
104 lines (98 loc) · 2.63 KB
/
HammingCode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
*
* Created by Peerachai Banyongrakkul Sec.1 5988070
* HammingCode.java
*/
import java.util.*;
public class HammingCode
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input the number of bits: ");
int n = sc.nextInt();
String temp = sc.nextLine();
System.out.print("Dataword: ");
String data = sc.nextLine();
if(data.length() != n)
{
System.out.println("Wrong input!! you must input "+n+" bits");
System.exit(0);
}
DataWord dataWord = new DataWord(data);
int a[] = encode(dataWord,n);
System.out.print("Codeword: ");
for(int i=0 ; i < a.length ; i++)
{
System.out.print(a[a.length-i-1]);
}
System.out.println();
System.out.print("Received codeword: ");
for(int i = 0; i< a.length ; i++)
{
//System.out.println("");
}
}
public static int[] encode(DataWord dataWord, int n)
{
int dataword[] = new int[n];
for(int i=0 ; i < n ; i++)
{
dataword[n-i-1] = Character.getNumericValue(dataWord.getData().charAt(i));
}
int codeword[];
int i=0, parityCount=0,j=0,k=0;
while(i<dataword.length)
{
if(Math.pow(2, parityCount) == i+parityCount + 1)
{
parityCount++;
}
else
{
i++;
}
}
codeword = new int[dataword.length + parityCount];
i = 1;
while(i<=codeword.length)
{
if(Math.pow(2, j) == i)
{
codeword[i-1] = 2;
j++;
}
else
{
codeword[k+j] = dataword[k++];
}
i++;
}
for(i = 0; i<parityCount ; i++)
{
codeword[((int) Math.pow(2,i)) - 1] = getParity(codeword,i);
}
return codeword;
}
public static int getParity(int b[], int power)
{
int parity = 0;
for(int i = 0 ; i<b.length ;i++)
{
if(b[i] != 2)
{
int k = i+1;
String s = Integer.toBinaryString(k);
int x = ((Integer.parseInt(s))/((int) Math.pow(10, power)))%10;
if(x == 1)
{
if(b[i] == 1)
{
parity = (parity+1)%2;
}
}
}
}
return parity;
}
}