-
Notifications
You must be signed in to change notification settings - Fork 2
/
2.Crc.java
93 lines (73 loc) · 2.9 KB
/
2.Crc.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//Write a program for error detecting code using CRC-CCITT(16-bits)
import java.util.Scanner;
public class CRC {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("At Sender Side: ");
// Input Data Stream
System.out.print("Enter message bits: ");
String message = sc.nextLine();
System.out.print("Enter generator: ");
String generator = sc.nextLine();
int data[] = new int[message.length() + generator.length() - 1];
int divisor[] = new int[generator.length()];
for (int i = 0; i < message.length(); i++)
data[i] = Integer.parseInt(message.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 < message.length(); i++) {
if (data[i] == 1) {
for (int j = 0; j < divisor.length; j++)
data[i + j] ^= divisor[j];
}
}
// Append the remainder to the original message
for (int i = 0; i < message.length(); i++)
data[i] = Integer.parseInt(message.charAt(i) + "");
// Display CRC
System.out.print("The checksum code is: ");
for (int i = 0; i < data.length; i++)
System.out.print(data[i]);
System.out.println();
System.out.println("At Receiver Side: ");
// Check for input CRC code
System.out.print("Enter checksum code: ");
message = sc.nextLine();
System.out.print("Enter generator: ");
generator = sc.nextLine();
data = new int[message.length() + generator.length() - 1];
divisor = new int[generator.length()];
for (int i = 0; i < message.length(); i++)
data[i] = Integer.parseInt(message.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 < message.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)
System.out.println("Data stream is valid");
else
System.out.println("Data stream is invalid. CRC error occurred.");
}
}
// fix the generator same at both sender and receiver side
// output:-
// At Sender Side:
// Enter message bits: 100100
// Enter generator: 1101
// The checksum code is: 100100001
// At Receiver Side:
// Enter checksum code: 11011
// Enter generator: 1101
// Data stream is invalid. CRC error occurred.