现在,我有以下代码来生成CRC-16 (Modbus)。我对CRC的概念相当陌生,我需要做一个CRC-8。这段代码能被修改成生成CRC-8吗?我的for循环从int = 1;开始,以i<tembByteList.Count - 1;结尾,因为我忽略了第一个和最后一个字节。
public List<byte> crc16(List<byte> tempByteList)
{
ushort reg_crc = 0xFFFF;
for(int i = 1; i<tempByteList.Count - 1; i++)
{
reg_crc ^= tempByteList[i];
for(int j = 0; j < 8; j++)
{
if((reg_crc & 0x01) == 1)
{
reg_crc = (ushort)((reg_crc >> 1) ^ 0xA001);
}
else
{
reg_crc = (ushort)(reg_crc >> 1);
}
}
}
tempByteList.Insert(tempByteList.Count - 1, (byte)((reg_crc >> 8) & 0xFF));
tempByteList.Insert(tempByteList.Count - 1, (byte)(reg_crc & 0xFF));
return tempByteList;
}发布于 2018-07-11 16:52:53
好的。只需将0xa001替换为0xe5,将初始化替换为零(ushort reg_crc = 0;)即可。这将产生蓝牙CRC-8。使用0x8c将生成Maxim 8.当然,您只需要在消息的末尾插入一个字节。
如果您希望使用使用所有1初始化的CRC,这将对消息中的初始零字符串敏感,那么您可以使用ROHCCRC-8,它将对多项式使用0xe0,并将reg_crc初始化为0xff。
顺便说一下,if语句可以由一个三元操作符代替,我认为它更易读:
reg_crc = (reg_crc & 1) != 0 ? (reg_crc >> 1) ^ POLY : reg_crc >> 1;https://stackoverflow.com/questions/51286751
复制相似问题