Skip to content

Create CRC16.java #3733

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/main/java/com/thealgorithms/others/CRC16.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.thealgorithms.others;

/**
* Generates a crc16 checksum for a given string
*/
public class 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();
}
}
23 changes: 23 additions & 0 deletions src/test/java/com/thealgorithms/others/CRC16Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.thealgorithms.others;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class CRC16Test {

CRC16 crc = new CRC16();

@Test
void testCRC16() {
// given
String textToCRC16 = "hacktoberfest!";

// when
String resultCRC16 = crc.crc16(textToCRC16); // Algorithm CRC16-CCITT-FALSE

// then
assertEquals("10FC", resultCRC16);
}

}