0

In this post: Print a string as hex bytes? I learned how to print as string into an "array" of hex bytes now I need something the other way around:

So for example the input would be: 73.69.67.6e.61.74.75.72.65 and the output would be a string.

Community
  • 1
  • 1
Eduard Florinescu
  • 16,747
  • 28
  • 113
  • 179

3 Answers3

3

you can use the built in binascii module. Do note however that this function will only work on ASCII encoded characters.

binascii.unhexlify(hexstr)

Your input string will need to be dotless however, but that is quite easy with a simple

string = string.replace('.','')

another (arguably safer) method would be to use base64 in the following way:

import base64
encoded = base64.b16encode(b'data to be encoded')
print (encoded)
data = base64.b16decode(encoded)
print (data)

or in your example:

data = base64.b16decode(b"7369676e6174757265", True)
print (data.decode("utf-8"))

The string can be sanitised before input into the b16decode method. Note that I am using python 3.2 and you may not necessarily need the b out the front of the string to denote bytes.

Example was found here

Serdalis
  • 10,296
  • 2
  • 38
  • 58
2

Without binascii:

>>> a="73.69.67.6e.61.74.75.72.65"  
>>> "".join(chr(int(e, 16)) for e in a.split('.'))  
'signature'  
>>>

or better:

>>> a="73.69.67.6e.61.74.75.72.65"  
>>> "".join(e.decode('hex') for e in a.split('.'))

PS: works with unicode:

>>> a='.'.join(x.encode('hex') for x in 'Hellö Wörld!')
>>> a
'48.65.6c.6c.94.20.57.94.72.6c.64.21'
>>> print "".join(e.decode('hex') for e in a.split('.'))
Hellö Wörld!
>>>

EDIT:

No need for a generator expression here (thx to thg435):

a.replace('.', '').decode('hex')
sloth
  • 99,095
  • 21
  • 171
  • 219
1

Use string split to get a list of strings, then base 16 for decoding the bytes.

>>> inp="73.69.67.6e.61.74.75.72.65"
>>> ''.join((chr(int(i,16)) for i in inp.split('.')))
'signature'
>>> 
gimel
  • 83,368
  • 10
  • 76
  • 104