获取字节数组的CRC校验和并将其添加到该字节数组 [英] Getting the CRC checksum of a byte array and adding it to that byte array
问题描述
我有这个字节数组:
static byte [] buf = new byte [] {(byte)0x01,(字节)0x04,(字节)0x00,(字节)0x01,(字节)0x00,(字节)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;
返回crc;
}
并使用Integer.toHexString()转换它们,但没有结果与正确的CRC匹配。有人可以指出我在CRC公式方面的正确方向。
请改用以下代码:
//计算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字节到最小sig。字节的crc
for(int i = 8; i!= 0; i--){//循环每一位
if((crc& 0x0001)!= 0) {//如果LSB设置为
crc>> = 1; //右移和XOR 0xA001
crc ^ = 0xA001;
}
else //其他LSB未设置
crc>> = 1; //只需向右移动
}
}
//注意,这个数字有低字节和高字节交换,所以相应地使用它(或交换字节)
return crc;
}
但是,您可能必须撤销返回CRC以获得正确的字节顺序。我甚至在这里测试过:
使用Windows计算器或其他东西,您可以看到第一个结果(来自上面的函数调用)给出了预期值(尽管是相反的)。 / p>
I have this byte array:
static byte[] buf = new byte[] { (byte) 0x01, (byte) 0x04, (byte)0x00, (byte)0x01,(byte)0x00, (byte) 0x01};
Now, the CRC checksum of this byte array is supposed to be 0x60, 0x0A. I want the Java code to recreate this checksum, however I cant seem to recreate it. I have tried 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;
}
and convert them using Integer.toHexString(), but none of the results match the correct CRC. Could someone please point me in the right direction in terms of CRC formula.
Use the following code instead:
// 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;
}
You may have to reverse your return CRC to get the right endianness, though. I even tested it here:
Using windows calculator or something you can see that the first result (from the above function call) gives the expected value (albeit reversed).
这篇关于获取字节数组的CRC校验和并将其添加到该字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!