Skip to content

Instantly share code, notes, and snippets.

@miho
Last active August 25, 2020 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miho/22139704ef77b90afcd696b7fe37736d to your computer and use it in GitHub Desktop.
Save miho/22139704ef77b90afcd696b7fe37736d to your computer and use it in GitHub Desktop.
Example on how to compute Arduino compliant CRC16 checksums in Java.
/**
* Example on how to compute Arduino compliant CRC16 checksums in Java.
*
* @author info@michaelhoffer.de
*/
public class Main {
public static void main(String[] args) {
byte[] data = new byte[]{1,2,3};
int crc = crc16(data);
String msg = String.format("CRC16: %x", crc);
System.out.println(msg);
}
/**
* Computes an Arduino compliant CRC16 checksum for the given data.
*
* Equivalent code on Arduino:
*
* <pre>
* #include <util/crc16.h>
* //...
* byte data[] = {1,2,3};
* uint16_t crc = 0xFFFF;
* for (uint32_t i = 0; i < sizeof(data); i++) {
* crc = _crc16_update(crc, data[i]);
* }
* Serial.println(crc, HEX); // shows 6161
* </pre>
*
* @param data byte array
* @return the CRC16 checksum for the specified data
*/
public static int crc16(final byte[] data) {
int crc = 0xFFFF;
for(byte a : data) {
crc ^= (a & 0xFF); // convert a to unsigned (otherwise, it does not work for a > 127)
for (int i = 0; i < 8; ++i)
{
if ((crc & 1) > 0)
crc = (crc >> 1) ^ 0xA001;
else
crc = (crc >> 1);
}
}
return crc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment