CRC32校验算法以及余式表生成

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
 
#define POLY 0x04C11DB7L
 
unsigned long get_sum_poly( unsigned char top_byte )
{
    /// sum all the polys at various offsets 
    unsigned long sum_poly = top_byte << 24;
    for( int j = 0; j < 8; ++ j )
    {
        /// check the top bit
        if( ( sum_poly >> 31 ) != 0 )
        {
            /// TODO : understand why '<<' first
            sum_poly = ( sum_poly << 1 ) ^ POLY;
        }
        else
        {
            sum_poly <<= 1;
        }
    }
 
    return sum_poly;
}
 
void create_table( unsigned long *table )
{
    for( int i = 0; i < 256; ++ i )
    {
        table[i] = get_sum_poly( (unsigned char) i );
    }
}
 
int main()
{
    /// the data 
    unsigned long data = 0x1011035b;
    /// load the register with the data
    unsigned long regi = 0;
    /// allocate memory to contain the AUGMENTED data (added some zeros)
    unsigned char p[4];
    /// copy data
    memcpy( p, &data, 4 );
 
    /// the table
    unsigned long table[256];
    /// create the table
    create_table( table );
 
    for (int i=0; i<256; i++)
    {
        if (i % 8 == 0)
        {
            printf("\n");
        }
        printf("0x%08x, ", table[i]);
    }
 
    /// because data contains 4 bytes
    for( int i = 0; i < 4; ++ i )
    {
        regi = ( regi << 8 ) ^ table[ ( regi >> 24 ) ^ p[i] ];
    }
 
    /// and now, register contains the remainder which is also called CRC value.
    printf("\ncrc32 = %08x\n", regi);
 
 
    return 0;
}
posted @ 2013-03-20 22:03  godjob  Views(2483)  Comments(0Edit  收藏  举报