CRC-32的C代碼


最近在研究ZIP,其中涉及到CRC循環冗余校驗,是對未壓縮數據的CRC驗證。CRC網上代碼比較亂,整理了一個發一下。

# include <stdio.h>
# include <string.h>


typedef unsigned int uint ;
uint POLYNOMIAL = 0xEDB88320 ;
int have_table = 0 ;
uint table[256] ;


void make_table()
{
    int i, j, crc ;
    have_table = 1 ;
    for (i = 0 ; i < 256 ; i++)
        for (j = 0, table[i] = i ; j < 8 ; j++)
            table[i] = (table[i]>>1)^((table[i]&1)?POLYNOMIAL:0) ;
}


uint crc32(uint crc, char *buff, int len)
{
    if (!have_table) make_table() ;
    crc = ~crc;
    for (int i = 0; i < len; i++)
        crc = (crc >> 8) ^ table[(crc ^ buff[i]) & 0xff];
    return ~crc;
}


int main ()
{
    char s[] = "aaaaaa";
    printf("%08Xh\n", crc32(0, s, strlen(s)));
    return 0 ;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM