使用方法:先調用init_crc32_tab生成查詢表,再調用calc_img_crc獲得文件的CRC值。
#define Poly 0xEDB88320L//CRC32標准 static unsigned int crc_tab32[256];//CRC查詢表 //生成CRC查詢表 void init_crc32_tab( void ) { int i, j; unsigned int crc; for (i=0; i<256; i++) { crc = (unsigned long)i; for (j=0; j<8; j++) { if ( crc & 0x00000001L ) crc = ( crc >> 1 ) ^ Poly; else crc = crc >> 1; } 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 >> 8)^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 -1; } const unsigned int size = 16 * 1024; unsigned char crcbuf[size]; DWORD rdlen; unsigned int crc = 0;//CRC初始值為0 while(ReadFile(hFile, crcbuf, size, &rdlen, NULL), rdlen) crc = get_crc32(crc, crcbuf, rdlen); *uiCrcValue = crc; CloseHandle(hFile); return 0; }