Skip to content

Commit b8d6b1a

Browse files
authored
Create CRC16.java (TheAlgorithms#3733)
* Create CRC16.java * Create CRC16Test.java
1 parent eb375a6 commit b8d6b1a

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.others;
2+
3+
/**
4+
* Generates a crc16 checksum for a given string
5+
*/
6+
public class CRC16 {
7+
8+
public static void main(String[] args) {
9+
System.out.println(crc16("Hello World!"));
10+
}
11+
12+
public static String crc16(String message) {
13+
int crc = 0xFFFF; // initial value
14+
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
15+
byte[] bytes = message.getBytes();
16+
17+
for (byte b : bytes) {
18+
for (int i = 0; i < 8; i++) {
19+
boolean bit = ((b >> (7 - i) & 1) == 1);
20+
boolean c15 = ((crc >> 15 & 1) == 1);
21+
crc <<= 1;
22+
if (c15 ^ bit)
23+
crc ^= polynomial;
24+
}
25+
}
26+
crc &= 0xffff;
27+
return Integer.toHexString(crc).toUpperCase();
28+
}
29+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.others;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
class CRC16Test {
8+
9+
CRC16 crc = new CRC16();
10+
11+
@Test
12+
void testCRC16() {
13+
// given
14+
String textToCRC16 = "hacktoberfest!";
15+
16+
// when
17+
String resultCRC16 = crc.crc16(textToCRC16); // Algorithm CRC16-CCITT-FALSE
18+
19+
// then
20+
assertEquals("10FC", resultCRC16);
21+
}
22+
23+
}

0 commit comments

Comments
 (0)