-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathHammingCode.java
More file actions
70 lines (54 loc) · 1.55 KB
/
HammingCode.java
File metadata and controls
70 lines (54 loc) · 1.55 KB
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
class HammingCode {
static void print(int ar[])
{
for (int i = 1; i < ar.length; i++) {
System.out.print(ar[i]);
}
System.out.println();
}
static int[] calculation(int[] ar, int r)
{
for (int i = 0; i < r; i++) {
int x = (int)Math.pow(2, i);
for (int j = 1; j < ar.length; j++) {
if (((j >> i) & 1) == 1) {
if (x != j)
ar[x] = ar[x] ^ ar[j];
}
}
System.out.println("r" + x + " = "
+ ar[x]);
}
return ar;
}
static int[] generateCode(String str, int M, int r)
{
int[] ar = new int[r + M + 1];
int j = 0;
for (int i = 1; i < ar.length; i++) {
if ((Math.ceil(Math.log(i) / Math.log(2))
- Math.floor(Math.log(i) / Math.log(2)))
== 0) {
ar[i] = 0;
}
else {
ar[i] = (int)(str.charAt(j) - '0');
j++;
}
}
return ar;
}
public static void main(String[] args)
{
String str = "0101";
int M = str.length();
int r = 1;
while (Math.pow(2, r) < (M + r + 1)) {
r++;
}
int[] ar = generateCode(str, M, r);
System.out.println("Generated hamming code ");
ar = calculation(ar, r);
print(ar);
}
}