# include <stdio.h>
# include <string.h>
unsigned int POLYNOMIAL = 0xEDB88320;
unsigned char have_table = 0;
unsigned int table[256];
void make_table()
{
int i, j;
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) ;
}
unsigned int crc32(unsigned int crc, char *buff, int len)
{
int i;
if (!have_table) make_table() ;
crc = ~crc;
for (i = 0; i < len; i++)
crc = (crc >> 8) ^ table[(crc ^ buff[i]) & 0xff];
return ~crc;
}
int crc32_file(char *filename, unsigned int *result)
{
FILE *file;
int len;
unsigned char buffer[1024];
//unsigned int crc = 0xffffffff;
unsigned int crc = 0x0;
if ((file = fopen (filename, "rb")) == NULL) {
printf("open %s fail here\n", filename);
return -1;
} else {
while ((len = fread (buffer, 1, 1024, file)) != 0) {
crc = crc32(crc, buffer, len);
}
*result = crc;
fclose (file);
return 0;
}
}
/*
int main(int argv, char **argc)
{
FILE *fp;
char s[] = "12345";
int ret = -1;
unsigned char digit[16];
char buf[256];
int i;
unsigned int result;
char cmd[256];
printf("start crc32 here~~~~~\n");
if (argv == 3) {
//ret = crc32_file(argc[1], digit);
ret = crc32_file(argc[1], &result);
if (ret == 0) {
printf("ret is 0x%x\n",result);
sprintf(cmd, "echo 0x%x > %s.%s",result, argc[1], argc[2]);
system(cmd);
} else {
printf("open %s fail\n", argc[1]);
}
} else {
printf("0X%08x\n", crc32(0, s, strlen(s)));
return -1;
}
return 0;
}
*/
头文件crc32.h
#ifndef __CRC32_H
#define __CRC32_H
#ifdef __cplusplus
extern "C"
{
#endif
extern unsigned int POLYNOMIAL;
extern unsigned char have_table;
extern unsigned int table[256];
void make_table(void);
int crc32_file(char *filename, unsigned int *result);
#ifdef __cplusplus
}
#endif
#endif