Created
July 9, 2018 20:50
-
-
Save atechcrew/4ab912d14578881d86466c3bd320daf4 to your computer and use it in GitHub Desktop.
Hamming Code in java. Error detection hamming code using java. Java code to detect error hamming code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.LinkedList; | |
import java.util.List; | |
public class HammingCode { | |
public static void main(String agrs[]){ | |
String data1 = "1001101"; | |
String data[] = data1.split(""); | |
String arr[] = calculateRdundancyBitValue(arrangeData(data), getNumbOfRedundancyBits(data.length)); | |
for(int i = 0; i < arr.length; i++){ | |
System.out.printf(arr[i]); | |
} | |
} | |
public static String[] calculateRdundancyBitValue(String arr[], int numberofRs){ | |
for(int i = 1; i <= numberofRs; i++){ | |
String s = ""; | |
int x = 1; | |
for(int k = 1; k < i; k++){ | |
x = x * 2; | |
} | |
for(int j = x - 1; j < arr.length; ){ | |
for(int k = 0; k < x; k++){ | |
if( j < arr.length){ | |
if(!(arr[j] == null)){ | |
s = s + arr[j]; | |
} | |
j++; | |
} | |
} | |
j = j + x; | |
} | |
arr[x-1] = checkParity(s) + ""; | |
} | |
List<String> array = new LinkedList<String>(Arrays.asList(arr)); | |
Collections.reverse(array); | |
return array.toArray(new String [array.size()]); | |
} | |
public static int checkParity(String s){ | |
int x = 0, zeros = 0, ones = 0; | |
String tempArr[] = s.split(""); | |
for(int i = 0; i < tempArr.length; i++){ | |
switch(tempArr[i]){ | |
case "1": | |
ones++; | |
break; | |
case "0": | |
zeros++; | |
break; | |
} | |
} | |
if((ones%2) != 0){ | |
x = 1; | |
}else{ | |
x = 0; | |
} | |
return x; | |
} | |
public static String[] arrangeData(String data[]){ | |
List<String> array = new LinkedList<String>(Arrays.asList(data)); | |
Collections.reverse(array); | |
data = array.toArray(new String [array.size()]); | |
String arr[] = new String[data.length + getNumbOfRedundancyBits(data.length)]; | |
int x = 1, j = 0; | |
for(int i = 1; i < arr.length + 1; i++){ | |
if(x == i){ | |
x = x * 2; | |
}else{ | |
arr[i-1] = data[j++]; | |
} | |
} | |
return arr; | |
} | |
public static int getNumbOfRedundancyBits(int m){ | |
int redundancyBit = 0; | |
int r = 1; | |
for(int i = 0; i < 100; i++){ | |
r = r * 2; | |
if(((i + m) + 1) < r){ | |
redundancyBit = i + 1; | |
break; | |
} | |
} | |
return redundancyBit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment