package assignment_2; /* Students: Lorenzo Casini (ID:10140), Edona Gashi(ID:11428) * * Hamming Code decoder and encoder. * Given an input string, the string is parsed and iterated one character * at a time. From each character we get its 8-bit ASCII representation * and we divide it into two 4-bits strings. We generate three parity bits for * each 4-bits string and we append the result to them in order to get a * 14-bits string for each character (4bits-3parity-4bits-3parity). Each * string is then written to a text file on different lines to ease retrieve * and decoding. * Encode is achieved by retrieving one line after another. Each line is a * string of 14 character, which is parsed again in 4-3-4-3 bits. We generate * again the parity bits on the 4-bits strings and we compare the 7-bits * retrieved string with the generated one. If equals, no error occurred. * Else we must look for errors. Depending on which parity bit we have a * difference with the generated one, we know where the error is and we * correct the corresponding bit of the retrieved string. * If the error is a parity bit, we don't care. They are deleted anyway so * we don't bother correcting those bits. * At this point we return only the correct two 4-bits packets, concatenate * them and we parse the string to decimal integer and cast to character, * to translate the decimal ASCII value in an actual character. * Character are then concatenated to get the original input string. * * The code is unable to detect/correct more than one error. */ import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class HammingCode { public static void main(String[] args) { // Input String String str = "Hello World!"; // Encode method and output to file encode(str, "output.txt"); // Prints decoded output taken from file System.out.println(decode("output.txt")); } private static void encode(String message, String filename){ // Local variables int length = message.length(); char currChar; String binaryString, frst4Bit, scnd4Bit; String decodedChar; try { // PrintWriter to write to file PrintWriter out = new PrintWriter(filename, "UTF-8"); // For each char of input string for(int i=0; i