c#生成一个带有字节数组输入的crc8字节方法
c# generating a crc8 byte method with a byte array input
现在我有以下代码来生成 CRC-16 (Modbus)。我对 CRC 的想法很陌生,我需要制作一个 CRC-8。可以修改此代码以生成 CRC-8 吗?我有一个从 int = 1;
开始并在 i<tembByteList.Count - 1;
结束的 for 循环,因为我忽略了第一个和最后一个字节。
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;
}
当然可以。只需将 0xa001
替换为 0xe5
,并将初始化替换为零 (ushort reg_crc = 0;
)。这将生成蓝牙 CRC-8。使用 0x8c
将生成 Maxim CRC-8。当然,您只需在消息末尾插入一个字节即可。
如果您更喜欢用全 1 初始化的 CRC,这对消息中的初始字符串零敏感,那么您可以使用 ROHC CRC-8,它将 0xe0
用于多项式,然后您会将 reg_crc
初始化为 0xff
.
顺便说一下,if
语句可以用三元运算符代替,我认为这样可读性更好:
reg_crc = (reg_crc & 1) != 0 ? (reg_crc >> 1) ^ POLY : reg_crc >> 1;
现在我有以下代码来生成 CRC-16 (Modbus)。我对 CRC 的想法很陌生,我需要制作一个 CRC-8。可以修改此代码以生成 CRC-8 吗?我有一个从 int = 1;
开始并在 i<tembByteList.Count - 1;
结束的 for 循环,因为我忽略了第一个和最后一个字节。
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;
}
当然可以。只需将 0xa001
替换为 0xe5
,并将初始化替换为零 (ushort reg_crc = 0;
)。这将生成蓝牙 CRC-8。使用 0x8c
将生成 Maxim CRC-8。当然,您只需在消息末尾插入一个字节即可。
如果您更喜欢用全 1 初始化的 CRC,这对消息中的初始字符串零敏感,那么您可以使用 ROHC CRC-8,它将 0xe0
用于多项式,然后您会将 reg_crc
初始化为 0xff
.
顺便说一下,if
语句可以用三元运算符代替,我认为这样可读性更好:
reg_crc = (reg_crc & 1) != 0 ? (reg_crc >> 1) ^ POLY : reg_crc >> 1;