Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class CRC{
- static String appendZeros(int n){ //append n zeros
- String str = "";
- for(int i = 0; i < n; i++) str += "0";
- return str;
- }
- static String removeZeros(String str){
- String result = "";
- for(int i = 0; i < str.length(); i++)
- if(str.charAt(i)=='1' && i!=0){
- result = str.substring(i);
- break;
- }
- return result;
- }
- static String exor(String a, String b){ //exor binary strings a and b
- String result = "";
- for(int i = 0; i < a.length(); i++)
- if(a.charAt(i) == b.charAt(i)) result += "0";
- else result += "1";
- return removeZeros(result);
- }
- static String getRemainder(String dividend, String divisor){//dividend%divisor
- String current = "";
- for(int i = 0; i < dividend.length(); i++){
- current += dividend.charAt(i);
- if(current.length() < divisor.length()) continue;
- else current = exor(current, divisor);
- }
- return appendZeros(divisor.length()-current.length()-1)+current;
- }
- public static void main(String args[]){
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter a binary message: ");
- String message = sc.next();
- System.out.print("Enter a generator polynomial(in binary): ");
- String divisor = sc.next();
- String remainder = getRemainder(message+appendZeros(divisor.length()-1), divisor);
- System.out.println("The string transmitted will be "+message+""+remainder);
- if(Integer.parseInt(getRemainder(message+remainder, divisor)) == 0) System.out.println("Success.");
- else System.out.println("Faliure.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement