Python CRC32 文件校验

 

binascii.crc32(s [,crc])
返回CRC32校验。参数'crc'指定初始值用于循环。例如:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
>>> import binascii
>>> crc = binascii.crc32('spam')
>>> binascii.crc32(' and eggs', crc)
739139840
>>> binascii.crc32('spam and eggs')
739139840

 

 

ContractedBlock.gif ExpandedBlockStart.gif Code
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  

 

 

ContractedBlock.gif ExpandedBlockStart.gif Code
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以上沒有這個問題.

 

 

ContractedBlock.gif ExpandedBlockStart.gif Code
from ctypes import * 
import binascii 

def getFileCRC(_path): 
try
blocksize 
= 1024 * 64 
= 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

 

 

转载于:https://www.cnblogs.com/leavingme/archive/2009/06/14/1503120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值