使用方法:先调用init_crc32_tab生成查询表,再调用calc_img_crc获得文件的CRC值。
#define Poly 0xEDB88320L//CRC32标准
static unsigned int crc_tab32[];//CRC查询表 //生成CRC查询表
void init_crc32_tab( void )
{
int i, j;
unsigned int crc; for (i=; i<; i++)
{
crc = (unsigned long)i;
for (j=; j<; j++)
{
if ( crc & 0x00000001L )
crc = ( crc >> ) ^ Poly;
else
crc = crc >> ;
}
crc_tab32[i] = crc;
}
}
//获得CRC
unsigned int get_crc32(unsigned int crcinit, unsigned char * bs, unsigned int bssize)
{
unsigned int crc = crcinit^0xffffffff; while(bssize--)
crc=(crc >> )^crc_tab32[(crc & 0xff) ^ *bs++]; return crc ^ 0xffffffff;
}
//获得文件CRC
int calc_img_crc(TCHAR *pFileName, unsigned int *uiCrcValue)
{
HANDLE hFile = CreateFile(pFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
return -;
} const unsigned int size = * ;
unsigned char crcbuf[size];
DWORD rdlen;
unsigned int crc = ;//CRC初始值为0 while(ReadFile(hFile, crcbuf, size, &rdlen, NULL), rdlen)
crc = get_crc32(crc, crcbuf, rdlen); *uiCrcValue = crc;
CloseHandle(hFile); return ;
}