Skip to content

Instantly share code, notes, and snippets.

@Rag0n
Last active May 30, 2018 18:24
Show Gist options
  • Save Rag0n/9395838 to your computer and use it in GitHub Desktop.
Save Rag0n/9395838 to your computer and use it in GitHub Desktop.
crc8 C implementation
// c = t%(m+1)
// T - итоговая сумма, M - макс допустимое значение контрольной суммы
#include <stdio.h>
#define MAX 256
#define POLYNOMIAL 0x81
FILE *file;
unsigned char crc8(unsigned int len)
{
unsigned char crc = 0x00, symbol = fgetc(file);
// int count = 0;
while (len--)
{
crc ^= symbol; // сложение
for (int bit = 8; bit > 0; --bit)
{
crc = (crc << 1);
if (crc & 0x80)
crc ^= POLYNOMIAL;
// crc = (crc << 1);
}
symbol = fgetc(file);
// count++;
// if (count == 999)
// {
// printf("%c\n", symbol);
// }
}
return crc;
}
int main()
{
int result, i = 0, symbol, count = 0;
file = fopen("text.txt", "r");
symbol = fgetc(file); // берет символ переноса
while(symbol != EOF)
{
i += symbol;
symbol = fgetc(file);
count++;
}
// printf("%d\n", i);
// printf("%d\n", count);
result = i%MAX;
printf("check sum: %d\n", result);
fclose(file);
file = fopen("text.txt", "r");
printf("CRC8: %d\n", crc8(count));
fclose(file);
return 0;
}
@rubenhorn
Copy link

There is a bug in line 21!
You need to extract the msb before shifting the crc:

int msb = (crc >> 7) & 1;
crc <<= 1
if(msb){
   crc ^= POLYNOMAL;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment