MxLDevs
MxLDevs

Reputation: 19506

Convert hex-string to string using binascii

By hex-string, it is a regular string except every two characters represents some byte, which is mapped to some ASCII char.

So for example the string

abc

Would be represented as

979899

I am looking at the binascii module but don't really know how to take the hex-string and turn it back into the ascii string. Which method can I use?

Note: I am starting with 979899 and want to convert it back to abc

Upvotes: 0

Views: 1385

Answers (3)

Blender
Blender

Reputation: 298046

You can use ord() to get the integer value of each character:

>>> map(ord, 'abc')
[97, 98, 99]
>>> ''.join(map(lambda c: str(ord(c)), 'asd'))
'979899'
>>> ''.join((str(ord(c)) for c in 'abc'))
'979899'

Upvotes: 3

halex
halex

Reputation: 16393

To get the string back from the hexadecimal number you can use

s=str(616263)
print "".join([chr(int(s[x:x+2], 16)) for x in range(0,len(s),2)])

See http://ideone.com/dupgs

Upvotes: 0

Sean Johnson
Sean Johnson

Reputation: 5607

You don't need binascii to get the integer representation of a character in a string, all you need is the built in function ord().

s = 'abc'
print(''.join(map(lambda x:str(ord(x)),s)))  # outputs "979899"

Upvotes: 2

Related Questions