获得文件的CRC32值

使用方法:先调用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;
}

 

转载于:https://www.cnblogs.com/milanleon/p/8805358.html

你可能感兴趣的:(前端,c/c++)