获取字节数组的CRC校验和并将其添加到该字节数组

问题描述

请使用以下代码

// Compute the MODBUS RTU CRC
private static int ModRTU_CRC(byte[] buf, int len)
{
  int crc = 0xFFFF;

  for (int pos = 0; pos < len; pos++) {
    crc ^= (int)buf[pos] & 0xFF;   // 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;  
}

但是,您可能必须反转返回的CRC才能获得正确的字节序。我什至在这里测试过:

http://ideone.com/PrBXVh

使用Windows计算器或其他工具,您可以看到第一个结果(来自上述函数调用)给出了预期值(尽管取反)。

解决方法

我有这个字节数组:

static byte[] buf = new byte[] { (byte) 0x01,(byte) 0x04,(byte)0x00,(byte)0x01,(byte) 0x01};

现在,假定此字节数组的CRC校验和为0x60、0x0A。我希望Java代码重新创建此校验和,但是我似乎无法重新创建它。我尝试了crc16:

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;

}

并使用Integer.toHexString()进行转换,但结果均不匹配正确的CRC。有人可以根据CRC公式指出我正确的方向。