10

我有这个字节数组:

static byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (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公式方面为我指出正确的方向。

4

3 回答 3

12

请改用以下代码:

// 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 计算器或其他工具,您可以看到第一个结果(来自上述函数调用)给出了预期值(尽管相反)。

于 2013-07-04T16:16:31.920 回答
4

CRC32会做吗,还是必须是CRC16?如果 32 没问题,您是否尝试过使用CRC32in java.util.zip

import java.util.zip.CRC32;

byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (byte) 0x01};
CRC32 crc32 = new CRC32();
crc32.update(buf);
System.out.printf("%X\n", crc32.getValue());

输出是:

F9DB8E67

然后,您可以在此之上进行任何您想要的额外计算。

于 2016-08-11T16:09:25.533 回答
2

我正在使用 Java 1.6 开发 modbus,尝试了上面的代码,但它只部分工作?同意某些 CRC,其他错误。我对其进行了更多研究,发现我在符号扩展方面遇到了问题。我掩盖了高位(参见下面的修复),现在效果很好。注意:所有 CRC 计算都不相同,MODBUS 有点不同:

    public static int getCRC(byte[] buf, int len ) {
    int crc =  0xFFFF;
    int val = 0;

      for (int pos = 0; pos < len; pos++) {
        crc ^= (int)(0x00ff & buf[pos]);  // FIX HERE -- 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, crc has low and high bytes swapped, so use it accordingly (or swap bytes)
    val =  (crc & 0xff) << 8;
    val =  val + ((crc >> 8) & 0xff);
    System.out.printf("Calculated a CRC of 0x%x, swapped: 0x%x\n", crc, val);
    return val;  

}   // end GetCRC
于 2015-01-10T15:35:01.367 回答