I am trying to calculate CRC for the first time. I have read a few pages that explain what is crc and how to calculate. Mainly this :
Could someone help me understand what is wrong here? Thanks in advance.
CodePudding user response:
You are missing a bit shift in the calculation. Change:
ACC = buf[byte];
to:
ACC = (unsigned)buf[byte] << 8;
Compare with this C# example code from Sunshine's Understanding and implementing CRC (Cyclic Redundancy Check) calculation:
public static ushort Compute_CRC16_Simple(byte[] bytes)
{
const ushort generator = 0x1021; /* divisor is 16bit */
ushort crc = 0; /* CRC value is 16bit */
foreach (byte b in bytes)
{
crc ^= (ushort(b << 8); /* move byte into MSB of 16bit CRC */
for (int i = 0; i < 8; i )
{
if ((crc & 0x8000) != 0) /* test for MSB = bit 15 */
{
crc = (ushort((crc << 1) ^ generator);
}
else
{
crc <<= 1;
}
}
}
return crc;
}
It uses a different initial value to your function, but note the line that XORs the byte into the MSB of the 16-bit CRC:
crc ^= (ushort(b << 8); /* move byte into MSB of 16bit CRC */