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

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公式吗?

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计算器或其他工具,你可以看到第一个结果(从上面的函数调用中)给出了期望值(尽管是反转的)。


4
CRC32可以使用吗?如果可以,您尝试使用java.util.zip中的CRC32了吗?如果必须使用CRC16,请忽略此建议。请注意保留HTML标记。
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

然后,您可以在此基础上进行任何其他计算。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接