CRC32 checksum in Python with hex input
20,306
Solution 1
I think you are looking for binascii.a2b_hex()
:
>>> binascii.crc32(binascii.a2b_hex('18329a7e'))
-1357533383
Solution 2
>>> import struct,binascii
>>> ncrc = lambda numVal: binascii.crc32(struct.pack('!I', numVal))
>>> ncrc(0x18329a7e)
-1357533383
Author by
dmranck
Updated on July 09, 2022Comments
-
dmranck almost 2 years
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 the 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!
-
miles82 about 13 yearsI doubt he wants to convert a list to a string like this. Replacing your second line with binascii.crc32(''.join(t)) gives the same result as phihag's answer.
-
dmranck about 13 yearsThanks! This is exactly what I needed. The results match up with an online crc calculator (lammertbies.nl/comm/info/crc-calculation.html). I didn't specify in the initial question, but I'm also looking for the output to be a string of 8 hex values. The following code formats the output correctly if anyone's wondering: '%08X' % (binascii.crc32(binascii.a2b_hex('18329a7e')) & 0xffffffff) Thanks again for the help!