使用如下python代码来计算文件的crc32值:
from zlib import crc32
import os
import sys
def getCrc32(filename):
with open(filename, 'rb') as f:
return crc32(f.read())
checksum=getCrc32(sys.argv[1])
print 'crc:',(hex(checksum))
python代码就是简洁,但是问题来了,运算了几个文件的crc:
结果有正有负,
python test.py system.img
crc:-0x30267351
python test.py usedata.img
crc:0xcf2fd49
查看python相关文档,说这个库函数结果是从-232到232之间。
我用另一断c++代码同样计算crc32的值,代码如下:
#include<string>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef TEST_CRC
#define BUFSIZE 1024*4
static const unsigned int crc_table[256] =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBF