forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCRC16.java
More file actions
32 lines (28 loc) · 865 Bytes
/
CRC16.java
File metadata and controls
32 lines (28 loc) · 865 Bytes
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
package com.thealgorithms.others;
/**
* Generates a crc16 checksum for a given string
*/
public final class CRC16 {
private CRC16() {
}
public static void main(String[] args) {
System.out.println(crc16("Hello World!"));
}
public static String crc16(String message) {
int crc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
byte[] bytes = message.getBytes();
for (byte b : bytes) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7 - i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) {
crc ^= polynomial;
}
}
}
crc &= 0xffff;
return Integer.toHexString(crc).toUpperCase();
}
}