tags:

views:

3864

answers:

3

I have a long sequence of hex digits in a string, such as

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?

+8  A: 

Try the binascii module

from binascii import unhexlify
bytes = unhexlify(myhexstr)
Crescent Fresh
Two ways to do it in 2.x, three ways in 3.x. So much for "there's only one way to do it"...
technomalogical
Other two ways are more 'built-in' so I would actually use one of those.
Crescent Fresh
@technomalogical: your comment is irrelevant to the answer; perhaps you should delete it and change it into a post to comp.lang.python .
ΤΖΩΤΖΙΟΥ
@technomalogical: I agree with ΤΖΩΤΖΙΟΥ. Also, you got it wrong. The correct phrase is: There should be one-- and preferably only one --*obvious* way to do it.
nosklo
+10  A: 

You can do this with the hex codec. ie:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'
Brian
Only works in 2.x, not 3.x.
Craig McQueen
+4  A: 
result = bytes.fromhex(some_hex_string)
vili
Only works in Python 3+ if I'm not mistaken
Triptych