zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    javascript中获取dom元素高度和宽度
    $.ajax()方法详解
    JQ中$(window).load和$(document).ready区别与执行顺序
    第几个幸运数
    乘积尾零
    星期一
    分数
    卡片换位
    冰雹数
    打印方格
  • 原文地址:https://www.cnblogs.com/UnGeek/p/2972148.html
Copyright © 2011-2022 走看看