File tree 2 files changed +52
-0
lines changed
main/java/com/thealgorithms/others
test/java/com/thealgorithms/others
2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments