现在把我把整个程序都连接上
目的是读一个文件 然后把这个文件用CRC算法进行计算,最后求出CRC码,不出错,但是结果不正确
请指教!谢谢
#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;
int i;
for(i = 1; i < (ch + 1); i++){
if(ref & 1)
value |= 1 << (ch - i);
ref >>= 1;
}
return value;
}
void init_crc32_table(){
unsigned long int crc,temp;
unsigned long int t1,t2;
unsigned long int flag;
int i,j;
for(i = 0; i <= 0xFF; i++){
temp=Reflect(i, 8);
crc32_table[i]= temp<< 24;
for (j = 0; j < 8; j++){
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);
}
return;
}
unsigned int cal_crc(unsigned char *ptr, unsigned char len)
{
unsigned int crc;
unsigned char da;
crc=0;
while(len--!=0) {
da=(unsigned char) (crc/256); /* 以8位二进制数的形式暂存CRC的高8位 */
crc<<=8; /* 左移8位,相当于CRC的低8位乘以 */
crc^=crc32_table[da^*ptr]; /* 高8位和当前字节相加后再查表求CRC ,再加上以前的CRC */
ptr++;
}
return(crc);
}
main()
{
unsigned char *str;
unsigned char len;
unsigned int crc32;
FILE *fp;
fp=fopen("crc32.txt","rb");
if(fp==NULL)
{
printf("Error!");
exit(-1);
}
fgets(str,strlen(str)+1,fp);
len= (unsigned char)(*str);
crc32=cal_crc(str,len);
printf("%xd",crc32);
getch();
}