Reputation: 119
Right now I have the following code to generate a CRC-16 (Modbus). I am rather new to the idea of CRC, and I need to make a CRC-8. Can this code be modified to generated a CRC-8? I have the for loop starting at int = 1;
and ending at i<tembByteList.Count - 1;
because I am ignoring the first and last byte.
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;
}
Upvotes: 0
Views: 1532
Reputation: 112209
Sure. Just replace 0xa001
with 0xe5
, and the initialization with zero (ushort reg_crc = 0;
). That will generate the Bluetooth CRC-8. Using 0x8c
will generate the Maxim CRC-8. And of course you'll only need to insert one byte into your message at the end.
If you would prefer a CRC that initializes with all ones, which would be sensitive to an initial string of zeros in the message, then you can use the ROHC CRC-8, which would use 0xe0
for the polynomial, and you would initialize reg_crc
to 0xff
.
By the way, the if
statement could be replaced by a a ternary operator, which I consider to be more readable:
reg_crc = (reg_crc & 1) != 0 ? (reg_crc >> 1) ^ POLY : reg_crc >> 1;
Upvotes: 1