(1)
(2) 代码版:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h> //NULL
struct CCRC32
{
unsigned int crc32_table[256]; // Lookup table arrays
unsigned int Reflect(unsigned int ref, char ch) // 初始化 crc32表 辅助函数
{
unsigned int value(0);
for (int i = 1; i < (ch + 1); i++) { // Swap bit 0 for bit 7 , bit 1 for bit 6, etc.
if (ref & 1)
value |= 1 << (ch - i);
ref >>= 1;
}
return value;
}
CCRC32() // 这是 CRC-32 在 PKZip、WinZip 和以太网中使用的官方多项式。
{ // This is the official polynomial used by CRC-32 in PKZip, WinZip and Ethernet.
unsigned int ulPolynomial = 0x04c11db7;
for (int i = 0; i <= 0xFF; i++) // 256 values representing ASCII character codes,0xFF = 255
{
crc32_table[i] = Reflect(i, 8) << 24;
for (int j = 0; j < 8; j++)
crc32_table[i] = (crc32_table[i] << 1) ^
(crc32_table[i] & (1 << 31) ? ulPolynomial : 0);
crc32_table[i] = Reflect(crc32_table[i], 32);
}
}
int Get_CRC(unsigned char* buffer, unsigned int dwSize)
{ // 用 crc32_table 寻找表来产生数据的 CRC 值。本函对 地址 buffer 开始的 dwSize 个字节生成检验码。
// Be sure to use unsigned variables, 一定要使用无符号变量,因为负值引入了需要零位的高位。
// because negative values introduce high bits where zero bits are required.
unsigned int crc(0xffffffff); int len = dwSize;
// Perform the algorithm on each character in the string, using the lookup table values.
while (len--)
crc = (crc >> 8) ^ crc32_table[(crc & 0xFF) ^ *buffer++];
return crc ^ 0xffffffff; // Exclusive OR the result with the beginning value.
}
};
(3) 以后再学习这个代码。
谢谢