CRC32校验算法(查表法)


CRC算法参数

CRC result width: 32 bits
Polynomial: 04C11DB7h
Initial value: FFFFFFFFh
Input data reflected: Yes
Result data reflected: Yes
XOR value: FFFFFFFFh


计算方法:

1.先要知道多项式是什么样子,以这个IEEE802.3标准CRC32多项式为例:x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x+ 1

2.转换成一个值

x32 则对应32bit = 1, x26 则对应26bit=1,得出一个值:(1<<32)|(1<<26)|(1<<23)|(1<<22)|…|(1<<1)|(1)=0x104C11DB7,对于CRC32取低32位,则=0x4C11DB7
3.用这个值通过一定方法生成长度为256的码表,对于CRC32表内每个元素都为32bit.

4.用一定的方法查表得出CRC32值。


验证Tool:

CRC在线计算


Source Code:

#include
using namespace std;

static unsigned long table[256];

//位逆转:

static unsigned long bitrev(unsigned long input, int bw)
{
int i;
unsigned long var;
var = 0;
for (i = 0; i {
if (input & 0x01)
{
var |= 1 << (bw - 1 - i);
}
input >>= 1;
}
return var;
}

//码表生成:
//如:X32+X26+…X1+1,poly=(1<<26)|…|(1<<1)|(1<<0)

void crc32_init(unsigned long poly)
{
int i;
int j;
unsigned long c;

poly = bitrev(poly, 32);
printf(“poly = 0x%08x\n\n”,poly); // 0xEDB88320
for (i = 0; i<256; i++) // 0x00-0xFF
{
c = i;
for (j = 0; j<8; j++) // bit 0-7
{
if (c & 1)
{
c = poly ^ (c >> 1);
}
else
{
c = c >> 1;
}
}
table[i] = c;
printf(" 0x%08x,", table[i]); //码表打印
if (3 == (i % 4))
{
printf("\n");
}
}
}

//计算CRC:

unsigned long crc32(unsigned long crc, void* input, int len)
{
int i;
unsigned char index;
unsigned char* pch;
pch = (unsigned char*)input;
for (i = 0; i {
index = (unsigned char)(crc^*pch);
crc = (crc >> 8) ^ table[index];
pch++;
}
return crc;
}

//测试用例:

void main(void)
{
unsigned long crc;
crc32_init(0x4C11DB7); //多项式
//char inputArr[32] = { 00, 0x5A, 00, 0x0E, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, 00, 0x10, 00, 01, 00, 0x20, 00, 01, 00, 0x10, 00, 00, 00, 0x80, 0x90 }; /* test 1*/
char inputArr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; /* test 2*/
crc = 0xFFFFFFFF;
//crc = crc32(crc, inputArr, 32); /* test 1*/
crc = crc32(crc, inputArr, 10); /* test 2*/
crc ^= 0xFFFFFFFF;
printf("\nCRC32=%08X\n\n", crc);
system(“pause”);
}

你可能感兴趣的:(算法)