CRC32 checksum in Python with hex input
I'm wanting to calculate the CRC32 checksum of a string of hex values in python. I found zlib.crc32(data) and binascii.crc32(data), but all 开发者_如何学Cthe examples I found using these functions have 'data' as a string ('hello' for example). I want to pass hex values in as data and find the checksum. I've tried setting data as a hex value (0x18329a7e for example) and I get a TypeError: must be string or buffer, not int. The function evaluates when I make the hex value a string ('0x18329a7e' for example), but I don't think it's evaluating the correct checksum. Any help would be appreciated. Thanks!
I think you are looking for binascii.a2b_hex()
:
>>> binascii.crc32(binascii.a2b_hex('18329a7e'))
-1357533383
>>> import struct,binascii
>>> ncrc = lambda numVal: binascii.crc32(struct.pack('!I', numVal))
>>> ncrc(0x18329a7e)
-1357533383
Try converting the list of hex values to a string:
t = ['\x18', '\x32', '\x9a', '\x7e']
chksum = binascii.crc32(str(t))
精彩评论