Simple implemetation of 16bit Cyclic Redundancy Check (CRC16) in C++
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define TABLE_SIZE 256
#define BUF_SIZE 7
#define POLYNOM 0xA001
void CreateLookUpTable(unsigned int* lookUp) {
unsigned int CRC = 0;
unsigned int shiftedCRC = 0;
for(int byteCount=0; byteCount < TABLE_SIZE; byteCount++) {
CRC = byteCount;
for(int bitCount=0; bitCount<8; bitCount++) {
shiftedCRC = CRC >> 1;
if((CRC & 0x01)==1)
CRC = shiftedCRC ^ POLYNOM;
else
CRC = shiftedCRC;
}
lookUp[byteCount] = CRC;
}
}
unsigned int CRCCompute(unsigned int* lookUp, unsigned int init, short* buffer, int length) {
unsigned int CRC = init;
unsigned int shiftedCRC = 0;
for(int pos = 0; pos < length; pos++) {
shiftedCRC = CRC >> 8;
CRC = shiftedCRC ^ lookUp[buffer[pos] ^ (CRC & 0xFF)];
}
return CRC;
}
int main(int argc, char* argv) {
short buffer[BUF_SIZE];
buffer[0] = 0xB2;
buffer[1] = 0x08;
buffer[2] = 0xFF;
buffer[3] = 0x01;
buffer[4] = 0x01;
buffer[5] = 0x81;
buffer[6] = 0x00;
unsigned int lookUp[TABLE_SIZE];
CreateLookUpTable(lookUp);
unsigned int crc = CRCCompute(lookUp, 0xFFFF, buffer, BUF_SIZE);
printf("CRC Hi: %X\nCRC Lo: %X",crc>>8, crc&0xFF);
getchar();
return TRUE;
}