gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:34:36 25 4
gpt4 key购买 nike

我有这个字节数组:

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 公式方面为我指出正确的方向吗?

最佳答案

改用下面的代码:

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

关于java - 获取字节数组的 CRC 校验和并将其添加到该字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17474223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com