Welcome, guest | Sign In | My Account | Store | Cart

Function becomes useful when we need hex value of crc32() result, even if it is negative.

Python, 15 lines
 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)

6 comments

Martin Miller 16 years, 4 months ago  # | flag

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:

import binascii

test='hello world! and Python too ;)'
crc=binascii.crc32(test)
print 'CRC:', crc
print 'CRC in hex: %08X' % crc

...RTFM?

panda gorl 15 years, 9 months ago  # | flag

even if is it negative? i don't think so

Thimo Kraemer 14 years, 2 months ago  # | flag

You could use the following statement:

'%08X' % (binascii.crc32(test) & 0xffffffff)

Denis Barmenkov (author) 12 years, 5 months ago  # | flag

Yes, it works. However, I prefer to use well-debugged function instead of using nuts-and-bolts in print statement. Thank you!

Michael Griffin 9 years, 1 month ago  # | flag

This works great.

However the million dollar question: If I use:

  1. test = 'some random string'
  2. crc32 = '%08X' % (binascii.crc32(test) & 0xffffffff)
  3. print crc32

I get: E6408FC7

How do I convert E6408FC7 or crc32 back to 'some random string'?

Thanks.

Denis Barmenkov (author) 9 years, 1 month ago  # | flag

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