當前位置:編程學習大全網 - 源碼破解 - CRC32 算法

CRC32 算法

為了提高編碼效率,在實際運用中大多采用查表法來完成CRC-32校驗,下面是產生CRC-32校驗嗎的子程序。

unsigned long crc_32_tab[256]={

0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,0x0edb8832,…, 0x5a05df1b, 0x2d02ef8d

};//事先計算出的參數表,***有256項,未全部列出。

unsigned long GenerateCRC32(char xdata * DataBuf,unsigned long len)

{

unsigned long oldcrc32;

unsigned long crc32;

unsigned long oldcrc;

unsigned int charcnt;

char c,t;

oldcrc32 = 0x00000000; //初值為0

charcnt=0;

while (len--) {

t= (oldcrc32 >> 24) & 0xFF; //要移出的字節的值

oldcrc=crc_32_tab[t]; //根據移出的字節的值查表

c=DataBuf[charcnt]; //新移進來的字節值

oldcrc32= (oldcrc32 << 8) | c; //將新移進來的字節值添在寄存器末字節中

oldcrc32=oldcrc32^oldcrc; //將寄存器與查出的值進行xor運算

charcnt++;

}

crc32=oldcrc32;

return crc32;

}

參數表可以先在PC機上算出來,也可在程序初始化時完成。下面是用於計算參數表的c語言子程序,在Visual C++ 6.0下編譯通過。

#include <stdio.h>

unsigned long int crc32_table[256];

unsigned long int ulPolynomial = 0x04c11db7;

unsigned long int Reflect(unsigned long int ref, char ch)

{ unsigned long int value(0);

// 交換bit0和bit7,bit1和bit6,類推

for(int i = 1; i < (ch + 1); i++)

{ if(ref & 1)

value |= 1 << (ch - i);

ref >>= 1; }

return value;

}

init_crc32_table()

{ unsigned long int crc,temp;

// 256個值

for(int i = 0; i <= 0xFF; i++)

{ temp=Reflect(i, 8);

crc32_table[i]= temp<< 24;

for (int j = 0; j < 8; j++){

unsigned long int t1,t2;

unsigned long int flag=crc32_table[i]&0x80000000;

t1=(crc32_table[i] << 1);

if(flag==0)

t2=0;

else

t2=ulPolynomial;

crc32_table[i] =t1^t2 ; }

crc=crc32_table[i];

crc32_table[i] = Reflect(crc32_table[i], 32);

}

}

  • 上一篇:立冬應該吃什麽?
  • 下一篇:安卓手機內存卡如何清理無用文件夾?
  • copyright 2024編程學習大全網