crc32校验文件数据

# 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


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值