CRC16-Berechnung in C mit Look-Up-Table
#include <stdio.h>
#define GPOLYNOM 0x8005 //x^16 + x^15 + x^2 + x^0
static unsigned short crc_tab16[256];
//Look-up table
// Die Tabelle enthält die Auswirkung der Rückkopplung für alle
// 256 mögliche Bitkombinationen in den obersten 8 Bit des Schieberegisters
void init_crc16_tab( void )
{
int i, j;
unsigned short crc; //16-Bit Variable
for (i=0; i<256; i++) {
crc = ((unsigned short) i) << 8;
for (j=0; j<8; j++) {
if ( crc & 0x8000 ) crc = ( crc << 1 ) ^ GPOLYNOM;
else crc = crc << 1;
}
crc_tab16[i] = crc;
}
}
#include <string.h>
int main(void)
{
int i;
char line[80];
unsigned short crc = 0;
fgets(line, 80, stdin);
init_crc16_tab();
for(i = 0; i<strlen(line)-1; i++){
// untere 8Bit des Registers nach oben schieben, Platz für neues Datenbyte
// Obere 8 Bit als Index für Tabelle um Korrekturwert zu ermitteln
crc = ((crc << 8) | line[i]) ^ crc_tab16[ (crc >> 8) & 0xff];
}
// noch zwei weitere Schritte, um angehängte Nullen zu verarbeiten
crc = ((crc << 8) | 0x00) ^ crc_tab16[ (crc >> 8) & 0xff];
crc = ((crc << 8) | 0x00) ^ crc_tab16[ (crc >> 8) & 0xff];
// Ausgabe CRC16
printf("CRC: %x\n", crc);
return 0;
}