2020-08-06 18:18:34 +08:00
|
|
|
#ifndef _CRC32_H_
|
|
|
|
#define _CRC32_H_
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
class CRC32 {
|
|
|
|
public:
|
|
|
|
CRC32() {
|
2020-08-06 18:18:34 +08:00
|
|
|
InitCRC32Table();
|
|
|
|
Reset();
|
|
|
|
}
|
|
|
|
|
|
|
|
virtual ~CRC32() {}
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
void Reset() {
|
2020-08-06 18:18:34 +08:00
|
|
|
m_currentCRC32 = 0xFFFFFFFF;
|
|
|
|
}
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
void ProcessBuffer(unsigned char* pBuffer, int bufferSize, int stride) {
|
2020-08-06 18:18:34 +08:00
|
|
|
// Perform the algorithm on each character
|
|
|
|
// in the string, using the lookup table values.
|
2021-09-08 10:54:22 +08:00
|
|
|
while(bufferSize > 0) {
|
2020-08-06 18:18:34 +08:00
|
|
|
m_currentCRC32 = (m_currentCRC32 >> 8) ^ m_crc32Table[(m_currentCRC32 & 0xFF) ^ *pBuffer];
|
|
|
|
|
|
|
|
pBuffer += stride;
|
|
|
|
bufferSize -= stride;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
unsigned int GetCRC() {
|
2020-08-06 18:18:34 +08:00
|
|
|
// Exclusive OR the result with the beginning value.
|
|
|
|
return m_currentCRC32 ^ 0xFFFFFFFF;
|
|
|
|
}
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
private:
|
2020-08-06 18:18:34 +08:00
|
|
|
|
|
|
|
// This is the official polynomial used by CRC-32
|
|
|
|
// in PKZip, WinZip and Ethernet.
|
|
|
|
static const unsigned int Polynomial = 0x04c11db7;
|
|
|
|
|
|
|
|
static const unsigned int CRC32TableSize = 256;
|
|
|
|
|
|
|
|
unsigned int m_crc32Table[CRC32TableSize]; // Lookup table array
|
|
|
|
|
|
|
|
unsigned int m_currentCRC32;
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
void InitCRC32Table() {
|
2020-08-06 18:18:34 +08:00
|
|
|
// 256 values representing ASCII character codes.
|
2021-09-08 10:54:22 +08:00
|
|
|
for(int i = 0; i <= CRC32TableSize; i++) {
|
2020-08-06 18:18:34 +08:00
|
|
|
m_crc32Table[i] = Reflect(i, 8) << 24;
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
for (unsigned int j = 0; j < 8; j++) {
|
2020-08-06 18:18:34 +08:00
|
|
|
m_crc32Table[i] = (m_crc32Table[i] << 1) ^ (m_crc32Table[i] & (1 << 31) ? Polynomial : 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
m_crc32Table[i] = Reflect(m_crc32Table[i], 32);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-08 10:54:22 +08:00
|
|
|
unsigned int Reflect(unsigned int ref, unsigned char numBits) {
|
2020-08-06 18:18:34 +08:00
|
|
|
unsigned int value = 0;
|
|
|
|
|
|
|
|
// Swap bit 0 for bit 7
|
|
|
|
// bit 1 for bit 6, etc.
|
2021-09-08 10:54:22 +08:00
|
|
|
for(unsigned char i = 1; i < (numBits + 1); i++) {
|
|
|
|
if(ref & 1) {
|
2020-08-06 18:18:34 +08:00
|
|
|
value |= 1 << (numBits - i);
|
|
|
|
}
|
|
|
|
|
|
|
|
ref >>= 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return value;
|
2021-09-08 10:54:22 +08:00
|
|
|
}
|
2020-08-06 18:18:34 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
#endif
|