Bart Friederichs
Bart Friederichs

Reputation: 33491

Converting a hex values to ASCII

What is the most 'Pythonic' way of translating

'\xff\xab\x12'

into

'ffab12'

I looked for functions that can do it, but they all want to translate to ASCII (so '\x40' to 'a'). I want to have the hexadecimal digits in ASCII.

Upvotes: 1

Views: 4147

Answers (2)

Jon Clements
Jon Clements

Reputation: 142106

There's a module called binascii that contains functions for just this:

>>> import binascii
>>> binascii.hexlify('\xff\xab\x12')
'ffab12'
>>> binascii.unhexlify('ffab12')
'\xff\xab\x12'

Upvotes: 5

Yotam Salmon
Yotam Salmon

Reputation: 2411

original = '\xff\xab\x12'
result = original.replace('\\x', '')
print result

It's \x because it's escaped. a.replace(b,c) just replaces all occurances of b with c in a.

What you want is not ascii, because ascii translates 0x41 to 'A'. You just want it in hexadecimal base without the \x (or 0x, in some cases)

Edit!!
Sorry, I thought the \x is escaped. So, \x followed by 2 hex digits represents a single char, not 4..

print "\x41"

Will print

A

So what we have to do is to convert each char to hex, then print it like that:

res = ""
for i in original:
   res += hex(ord(i))[2:].zfill(2)
print res

Now let's go over this line:

hex(ord(i))[2:]

ord(c) - returns the numerical value of the char c
hex(i) - returns the hex string value of the int i (e.g if i=65 it will return 0x41.
[2:] - cutting the "0x" prefix out of the hex string.
.zfill(2) - padding with zeroes

So, making that with a list comprehension will be much shorter:

result = "".join([hex(ord(c))[2:].zfill(2) for c in original])
print result

Upvotes: 0

Related Questions