3

I have a hex stream like: 1a2b3c4d5e6f7g but longer I want to split it into 2char hex values in a list, and then convert them to ascii.

dxc
  • 63
  • 1
  • 4

3 Answers3

5

What about binascii.unhexlify(hexstr)?
See the docs for the binascii module : http://docs.python.org/library/binascii.html

gion_13
  • 41,171
  • 10
  • 96
  • 108
3

In Python 2.x you can use binascii.unhexlify:

>>> import binascii
>>> binascii.unhexlify('abcdef0123456789')
'\xab\xcd\xef\x01#Eg\x89'

In Python 3 there's a more elegant method using only the built-in bytes type:

>>> bytes.fromhex('abcdef0123456789')
b'\xab\xcd\xef\x01#Eg\x89'
Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
  • it seems to have also another name: a2b_hex >>>binascii.a2b_hex('abcdef0123456789') Out[0]: '\xab\xcd\xef\x01#Eg\x89' – fabrizioM Sep 09 '11 at 17:40
2

One liner:

a = "1a2b3c"
print ''.join(chr(int(a[i] + a[i+1], 16)) for i in xrange(0, len(a), 2))

Explanation:

xrange(0, len(a), 2) # gives alternating indecis over the string
a[i] + a[i+1]        # the pair of characters as a string
int(..., 16)         # the string interpreted as a hex number
chr(...)             # the character corresponding to the given hex number
''.join()            # obtain a single string from the sequence of characters
UncleZeiv
  • 18,272
  • 7
  • 49
  • 77