CRC (Java)

Problem Definition: Write a program in Java to find CRC of a given number.

import java.util.Scanner;
class CRC{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//Input Data Stream
System.out.print(“Enter data stream: “);
String datastream = sc.nextLine();
System.out.print(“Enter generator: “);
String generator = sc.nextLine();
int data[] = new int[datastream.length() + generator.length() – 1];
int divisor[] = new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i] = Integer.parseInt(datastream.charAt(i)+””);
for(int i=0;i<generator.length();i++)
divisor[i] = Integer.parseInt(generator.charAt(i)+””);

//Calculation of CRC
for(int i=0;i<datastream.length();i++){
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}

//Display CRC
System.out.print(“The CRC code is: “);
for(int i=0;i<datastream.length();i++)
data[i] = Integer.parseInt(datastream.charAt(i)+””);
for(int i=0;i<data.length;i++) System.out.print(data[i]);
System.out.println();
//Check for input CRC code
System.out.print(“Enter CRC code: “);
datastream = sc.nextLine();
System.out.print(“Enter generator: “);
generator = sc.nextLine();
data = new int[datastream.length() + generator.length() – 1];
divisor = new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i] = Integer.parseInt(datastream.charAt(i)+””);
for(int i=0;i<generator.length();i++)
divisor[i] = Integer.parseInt(generator.charAt(i)+””);

//Calculation of remainder
for(int i=0;i<datastream.length();i++){
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}

//Display validity of data
boolean valid = true;
for(int i=0;i<data.length;i++)
if(data[i]==1){
valid = false;
break;
}

if(valid==true) System.out.println(“Data stream is valid”);
else System.out.println(“Data stream is invalid. CRC error occured.”);
}
}

/*Output

Enter data stream: 101010
Enter generator: 11111
The CRC code is: 1010101010
Enter CRC code: 1010100010
Enter generator: 11111
Data stream is invalid. CRC error occured.
*/

Advertisements

2 thoughts on “CRC (Java)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s