faqts : Computers : Programming : Languages : Python : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

58 of 105 people (55%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

How to convert hex string to ascii string?

May 14th, 2001 14:25
Grant Glouser, Alwyn Schoeman,


Sometimes you want to convert a string like "777777" to "www".  One 
example of this is when you get binary data on a socket and use 
binascii.b2a_hex() to get a hex string.

If anyone knows of a better way to go directly from the binary to the 
ascii, please comment.

The code:

def hextranslate(s):
        res = ""
        for i in range(len(s)/2):
                realIdx = i*2
                res = res + chr(int(s[realIdx:realIdx+2],16))
        return res

if you then do:
print hextranslate("777777")
You would get:
www

----
One easier approach would be to use binascii.a2b_hex(), which does
exactly the same thing as your hextranslate.  But it's already written
in the binascii module!
>>> binascii.a2b_hex('777777')
'www'

The documentation of the binascii module suggests that this will be
faster than doing it yourself (with a function like hextranslate),
possibly because it is implemented in C.  I haven't done any timing
tests, so I can't confirm this.

Another thing you may notice in the documentation is that a2b_hex is the
inverse of b2a_hex.  In other words, a2b_hex(b2a_hex(s)) == s.
>>> s = 'www'
>>> s2 = b2a_hex(s)
>>> s2
'777777'
>>> s3 = a2b_hex(s2)
>>> s3
'www'

Think about this!  If you get "binary" data from a socket, convert it to
a hex representation with b2a_hex, then convert it back with a2b_hex or
hextranslate, you get exactly the same data you started with.  The
"binary data" you get from a socket is just a Python string, after all,
and it's probably exactly what you needed.  No need to convert at all!