>>> import binascii
>>> crc = binascii.crc32('spam')
>>> binascii.crc32(' and eggs', crc)
739139840
>>> binascii.crc32('spam and eggs')
739139840
import binascii
def getFileCRC(_path):
try:
blocksize = 1024 * 64
f = open(_path,"rb")
str = f.read(blocksize)
crc = 0
while(len(str) != 0):
crc = binascii.crc32(str, crc)
str = f.read(blocksize)
f.close()
except:
print 'get file crc error!'
return 0
return crc
python 2.X的crc32實作上跟一般的C實作上在整數有號無號的處理上略有不同, 所以使用python 2.X與一般C實作算出的crc32(如sfv)比對時,通常需要特別的方法,
這邊列出一個透過zlib.crc32快速得到所需要結果的方法:
import zlib
def crc32(st):
crc = zlib.crc32(st)
if crc > 0:
return "%x" % (crc)
else:
return "%x" % (~crc ^ 0xffffffff)
ex1 = "12345"
ex2 = "1kcaseztsa12345azy"
print "%x" % zlib.crc32(ex1)
print crc32(ex1)
print "%x" % zlib.crc32(ex2)
print crc32(ex2)
或如果你有ctypes的話:
import zlib
import ctypes
def crc32_c(st):
return "%x" % ctypes.c_uint32(zlib.crc32(st)).value
ex1 = "12345"
ex2 = "1kcaseztsa12345azy"
print "%x" % zlib.crc32(ex1)
print crc32_c(ex1)
print "%x" % zlib.crc32(ex2)
print crc32_c(ex2)
註: python 3.0以上沒有這個問題.
from ctypes import *
import binascii
def getFileCRC(_path):
try:
blocksize = 1024 * 64
f = open(_path,"rb")
str = f.read(blocksize)
crc = 0
while(len(str) != 0):
crc = binascii.crc32(str, crc)
str = f.read(blocksize)
f.close()
except:
klog.error("get file crc error!")
return 0
return c_uint(crc).value