ActiveState Code

Recipe 521907: binascii.crc32 result to hex


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

Python
 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)

Comments

  1. 1. At 10:42 a.m. on 28 nov 2007, Martin Miller said:

    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?

  2. 2. At 3:17 p.m. on 23 jul 2008, panda gorl said:

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

Sign in to comment