I'm trying to get the CRC16 algorithm going in Java... but I must admit bitwise operations aren't my strong point. This is what I've done with the EKM-provided CRC16 C-code (an attempt to translate it to Java) :
Code: Select all
public void tryMe(byte[] responseFromDevice)
{
byte[] c = new byte[2];
c[0] = a[253];
c[1] = a[254];
log("EKM CRC : " + Integer.toHexString(ekmCheckCrc(responseFromDevice)) +
" Device CRC : " + Integer.toHexString((int) (c[0])) + Integer.toHexString((int) (c[1])) );
}
public int ekmCheckCrc(byte[] dat) {
int crc = 0xffff;
for (int i = 1; i < dat.length-3; i++) {
crc = (crc >>> 8) ^ ekmCrcLut[(crc ^ dat[i]) & 0xff];
}
crc = (crc >>> 8) | (crc << 8);
crc = crc & 0x7f7f;
return crc;
}
static int[] ekmCrcLut = new int[]{
0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
(EKM's LUT sits here, no point including the rest of it)
0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040
};
Here's someone else's code, which uses the same LUT :
Code: Select all
public class CRC16 {
public void checksum(byte[] a) {
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
...the same LUT as the one EKM uses goes here... no point including all of it...
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
byte[] bytes = a;
int crc = 0x0000;
for (byte b : bytes) {
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
}
System.out.println("CRC16 = " + Integer.toHexString(crc));
}
}
What am I doing wrong ? Thanks in advance