I am currently working on a project, having an embedded system sending data to a PC via radio. The packets get a crc16 checksum at the end and it\'s calculated based on this
The major difference between java and c in this case is the fact in c you use unsigned numbers and java has only signed numbers. While you can implement the same algorithm with signed numbers, you have to be aware of the fact the sign bit is carried over on shift operations, requiring an extra "and".
This is my implementation:
static int crc16(final byte[] buffer) {
int crc = 0xFFFF;
for (int j = 0; j < buffer.length ; j++) {
crc = ((crc >>> 8) | (crc << 8) )& 0xffff;
crc ^= (buffer[j] & 0xff);//byte to int, trunc sign
crc ^= ((crc & 0xff) >> 4);
crc ^= (crc << 12) & 0xffff;
crc ^= ((crc & 0xFF) << 5) & 0xffff;
}
crc &= 0xffff;
return crc;
}