Last active
December 10, 2019 14:22
-
-
Save sidsbrmnn/85021b1d9540c8ecce4850789a22e2c7 to your computer and use it in GitHub Desktop.
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.Scanner; | |
public class Crc { | |
static Scanner sc = new Scanner(System.in); | |
static void readArray(int[] arr) { | |
for (int i = 0; i < arr.length; i++) { | |
arr[i] = sc.nextInt(); | |
} | |
} | |
static void calculateCrc(int[] generator, int[] remainder) { | |
int current = 0; | |
while (remainder.length - current >= generator.length) { | |
for (int i = 0; i < generator.length; i++) { | |
remainder[current + i] ^= generator[i]; | |
} | |
while (remainder[current] == 0 && current != remainder.length - 1) { | |
current++; | |
} | |
} | |
} | |
static boolean isValidCrc(int[] remainder) { | |
for (int item : remainder) { | |
if (item != 0) return false; | |
} | |
return true; | |
} | |
public static void main(String[] args) { | |
System.out.print("Enter no of data bits: "); | |
int[] dataWord = new int[sc.nextInt()]; | |
System.out.println("Enter data bits:"); | |
readArray(dataWord); | |
System.out.print("Enter no of generator bits: "); | |
int[] generator = new int[sc.nextInt()]; | |
System.out.println("Enter generator bits:"); | |
readArray(generator); | |
int totalBits = dataWord.length + generator.length - 1; | |
int[] codeWord = new int[totalBits]; | |
int[] remainder = new int[totalBits]; | |
System.arraycopy(dataWord, 0, codeWord, 0, dataWord.length); | |
System.out.print("Dividend:"); | |
for (int item : codeWord) { | |
System.out.print(" " + item); | |
} | |
System.out.println(); | |
System.arraycopy(codeWord, 0, remainder, 0, codeWord.length); | |
computeCrc(generator, remainder); | |
for (int i = 0; i < totalBits; i++) { | |
codeWord[i] ^= remainder[i]; | |
} | |
System.out.print("Transmitted code word:"); | |
for (int item : codeWord) { | |
System.out.print(" " + item); | |
} | |
System.out.println(); | |
System.out.print("Enter a new code word:"); | |
readArray(codeWord); | |
System.arraycopy(codeWord, 0, remainder, 0, codeWord.length); | |
computeCrc(generator, remainder); | |
if (isValidCrc(remainder)) { | |
System.out.println("No error"); | |
} else { | |
System.out.println("ERROR"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment