Skip to content

Instantly share code, notes, and snippets.

@jadamcrain
Created June 26, 2010 12:53
Show Gist options
  • Select an option

  • Save jadamcrain/454032 to your computer and use it in GitHub Desktop.

Select an option

Save jadamcrain/454032 to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <time.h>
#include <iostream>
#include <ctime>
unsigned int CalcCRC(const unsigned char* aInput, size_t aLength, const unsigned int* apTable)
{
unsigned int CRC = 0;
for(size_t i=0; i<aLength; i++) {
CRC = apTable[(CRC ^ aInput[i]) & 0xFF]^(CRC >> 8);
}
return (~CRC) & 0xFFFF;
}
void PrecomputeCRC(unsigned int* apTable)
{
unsigned int i, j, CRC;
for(i = 0; i < 256; i++) {
CRC = i;
for (j = 0; j < 8; ++j) {
if(CRC & 0x0001) CRC = (CRC >> 1) ^ 0xA6BC;
else CRC >>= 1;
}
apTable[i] = CRC;
}
}
int main(int argc, char** argv)
{
//setup the table and prove the crc is working correctly
unsigned int table[256];
PrecomputeCRC(table);
unsigned char header[8] = {0x05, 0x64, 0x05, 0xC0, 0x01, 0x00, 0x00, 0x04};
assert(CalcCRC(header, 8, table) == 0x21E9);
size_t iter = 100*(1<<20);
clock_t start = std::clock();
for(size_t i=0; i<iter; ++i) CalcCRC(header, 8, table);
clock_t stop = std::clock();
std::cout << (stop-start) << " ms " << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment