1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef unsigned short int u16;
typedef unsigned char u8;
void addToCrc(u8 word, u16* crcptr)
{
*crcptr = (*crcptr >> 8) | (*crcptr << 8);
*crcptr ^= (u8)word;
*crcptr ^= (*crcptr & 0xff) >> 4;
*crcptr ^= (*crcptr << 8) << 4;
*crcptr ^= ((*crcptr & 0xff) << 4) << 1;
}
int main(int argc, char** argv)
{
u16 crc;
u16 idx = 0;
u16 computed_crc;
u8 data[] = {6, 0, 2, 4, 8, 0, 0, 0};// 110 0000 0010 0100 1000 0000 0000 0000
// verifies that u16 is 2 bytes width
assert(sizeof crc == 2);
// initializes crc
crc = 0x1234; // Any 16 bits value is correct! The received MUST HAVE THE SAME INIT VALUE as the transmitter
// crc computing
while(idx < sizeof(data))
{
addToCrc(data[idx++], &crc);
}
// add computed crc to crc
computed_crc = crc;
printf("computed crc = %03x\n", crc);
addToCrc(computed_crc >> 8, &crc);
addToCrc(computed_crc & 0xff, &crc);
printf("crc = %04x\n", crc);
// MUST BE ZERO!
assert(crc == 0);
return 0;
} |