Function becomes useful when we need hex value of crc32() result, even if it is negative.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import binascii
def crc2hex(crc):
res=''
for i in range(4):
t=crc & 0xFF
crc >>= 8
res='%02X%s' % (t, res)
return res
if __name__=='__main__':
test='hello world! and Python too ;)'
crc=binascii.crc32(test)
print 'CRC:', crc
print 'CRC in hex:', crc2hex(crc)
|
Tags: algorithms
A special formatting function is not needed. You can easily convert a 32 bit numeric value into an 8 byte hex string without writting a special function to do it by just using string objects' built-in %operator.
Note the final line in the following:
...RTFM?
even if is it negative? i don't think so
You could use the following statement:
'%08X' % (binascii.crc32(test) & 0xffffffff)
Yes, it works. However, I prefer to use well-debugged function instead of using nuts-and-bolts in print statement. Thank you!
This works great.
However the million dollar question: If I use:
I get:
E6408FC7
How do I convert
E6408FC7
orcrc32
back to'some random string'
?Thanks.
Hi Michael, it is impossible to restore source string from CRC32, you only can brute force strings which have the same CRC32 value ;).
See also: http://en.wikipedia.org/wiki/Hash_function#Non-invertible