I am trying to modify that piece of code to make it work with arbitrary values and lengths.
My modification so far:
public static int ModRTU_CRC(final byte[] buf, int crc)
{
final int len = buf.length;
for (int pos = 0; pos < len; pos++)
{
crc ^= buf[pos]; // XOR byte into least sig. byte of crc
for (int i = 8; i != 0; i--)
{ // Loop over each bit
if ((crc & 0x0001) != 0)
{ // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else
{
// Else LSB is not set
crc >>= 1; // Just shift right
}
}
}
// Note, this number has low and high bytes swapped, so use it
// accordingly (or swap bytes)
return crc;
}
I'm testing my code in the following way:
final String a = "1101011011";
final String crc = "10011";
final int parsedA = Integer.parseInt(a, 2);
final ByteBuffer parsedBytes = ByteBuffer.allocate(4).putInt(parsedA);
final byte[] array = parsedBytes.array();
final int parsedCRC = Integer.parseInt(crc, 2);
System.out.println(Integer.toBinaryString(ModRTU_CRC(array, parsedCRC)));
I get 1000111101000101
but the correct answer is 11010110111110
. Even if i swap bytes i don't get to the goal. Can you help me please to figure out where i made a mistake?