How can I unpack binary hex formatted data in Python?

binary, hex, python

Solution

There's an easy way to do this with the `binascii` module:

>>> import binascii
>>> print binascii.hexlify("ABCZ")
'4142435a'
>>> print binascii.unhexlify("4142435a")
'ABCZ'

Unless I'm misunderstanding something about the nibble ordering (high-nibble first is the default… anything different is insane), that should be perfectly sufficient!

Furthermore, Python's `hashlib.md5` objects have a `hexdigest()` method to automatically convert the MD5 digest to an ASCII hex string, so that this method isn't even necessary for MD5 digests. Hope that helps.

Problem

Using the PHP pack() function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the unpack() function with the H* format flag. How would I unpack this data in Python?

Original source