I am trying to get right CRC16 with using the following code,
public static int GenCrc16(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;
}
if I pass a string,
String input = "00000140 0000000 000000002 0000001";
I get 0x17B5 which is correct but I want pass data as as raw data
long[] inputLongArray= {0x00000140, 0x00000000, 0x00000002, 0x00000001}
public static byte[] toByte(long[] longArray) {
ByteBuffer bb = ByteBuffer.allocate(longArray.length * Long.BYTES);
bb.asLongBuffer().put(longArray);
return bb.array();
}
I am expecting 0x1F19 as per https://crccalc.com with following 00000140 00000000 00000002 00000001 and choose hex data type and CRC-16/CCITT-FALSE.
public static void main(String[] args) {
long[] intputarray = {0x00000140, 0x0000000, 0x000000002, 0x0000001};
System.out.println(Integer.toHexString(GenCrc16(toByte(intputarray)));
}
What I am doing wrong. Thanks in advance for help.
long
values are 8 bytes, aka 16 hex digits, so
long[] {0x00000140, 0x00000000, 0x00000002, 0x00000001}
is same as
"0000000000000140 0000000000000000 0000000000000002 0000000000000001"
and both have CRC-16/CCITT-FALSE value
E47B
The string
"00000140 0000000 000000002 0000001"
should really be
"00000140 00000000 00000002 00000001"
which is the same as
int[] {0x00000140, 0x00000000, 0x00000002, 0x00000001}
and both have CRC-16/CCITT-FALSE value
1F19
public static byte[] toByte(final int... intArray) {
ByteBuffer bb = ByteBuffer.allocate(intArray.length * Integer.BYTES);
bb.asIntBuffer().put(intArray);
return bb.array();
}
User contributions licensed under CC BY-SA 3.0