Advertisement
Shailrshah

Cyclic Redundancy Check(CRC)

Mar 5th, 2014
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. import java.util.Scanner;
  2. class CRC{
  3.     static String appendZeros(int n){ //append n zeros
  4.         String str = "";
  5.         for(int i = 0; i < n; i++) str += "0";
  6.         return str;
  7.     }
  8.     static String removeZeros(String str){
  9.         String result = "";
  10.         for(int i = 0; i < str.length(); i++)
  11.             if(str.charAt(i)=='1' && i!=0){
  12.                 result = str.substring(i);
  13.                 break;
  14.             }
  15.         return result;
  16.     }
  17.     static String exor(String a, String b){ //exor binary strings a and b
  18.         String result = "";
  19.         for(int i = 0; i < a.length(); i++)
  20.             if(a.charAt(i) == b.charAt(i)) result += "0";
  21.             else result += "1";
  22.         return removeZeros(result);
  23.     }
  24.     static String getRemainder(String dividend, String divisor){//dividend%divisor
  25.         String current = "";
  26.         for(int i = 0; i < dividend.length(); i++){
  27.             current += dividend.charAt(i);
  28.             if(current.length() < divisor.length()) continue;
  29.             else current = exor(current, divisor);
  30.         }
  31.         return appendZeros(divisor.length()-current.length()-1)+current;
  32.     }
  33.     public static void main(String args[]){
  34.         Scanner sc = new Scanner(System.in);
  35.         System.out.print("Enter a binary message: ");
  36.         String message = sc.next();
  37.         System.out.print("Enter a generator polynomial(in binary): ");
  38.         String divisor = sc.next();
  39.         String remainder = getRemainder(message+appendZeros(divisor.length()-1), divisor);
  40.         System.out.println("The string transmitted will be "+message+""+remainder);
  41.         if(Integer.parseInt(getRemainder(message+remainder, divisor)) == 0) System.out.println("Success.");
  42.         else System.out.println("Faliure.");
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement