Link to home
Start Free TrialLog in
Avatar of CSecurity
CSecurityFlag for Iran, Islamic Republic of

asked on

Hex string to ascii string

Hi

I have a string like this:

AAABACADAF0406A6A8A7A2A5

so a for loop needed to get 2 byte 2byte and convert each to ascii and store all in a variable.

I'm not so good in Python, so please advice.

Thanks from now
Avatar of pepr
pepr

Firstly, the values are not ASCII as the 8th bit is often set. What is the encoding?

There may be more methods to do that. The question is what is the motivation, what is the source of the data. You may be interested in low-level standard module binascii (http://docs.python.org/library/binascii.html#module-binascii) or in higher-level modules like base 64, binhex, uu (see the references at the bottom of the page).
Do I understand it well that you have a string 'AAABACADAF0406A6A8A7A2A5', then you want to get 'AA' substring, assuming it is a hex description of a byte you want to get decimal number (170) and convert it to the character in your encoding... ?
Avatar of CSecurity

ASKER

yes
Well, what character should be AA ? (What encoding do you use?)
Here is an untested guess (assuming straight conversion to ASCII).
hexString = 'AAABACADAF0406A6A8A7A2A5'
result = ''
for x in range(0, len(hexString), 2):
  pair = hexString[x:x+2]
  numeric = int(pair, 16)
  ch = ord(numeric)
  result += ch

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jdevera
jdevera
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well, the ramrom's solution is the classical one (if no binascii module were here). The jdevera solution is overcomplicated. There is no need to cut the myhex to couples and join the results. See the snippet below.

Still, the question is whether the result is ASCII (it cannot be) and what it really is. The unhexlify() simply returns the binary result and cannot be reliably interpreted as ASCII or as a string at all. It will be more apparent in Python 3.0 where strings are always Unicode.
import binascii
src = 'AAABACADAF0406A6A8A7A2A5'
s = binascii.unhexlify(src)
print s

Open in new window

That's actually very good pepr, much better than my solution; you should get the points.

In regards to the ASCII or not ASCII question, maybe all they wanted was to have the values in a string, or maybe they made this string up as an example.
jdevera: No problem here. No need to fiddle with the points ;)

For the ASCII/non-ASCII the problem is that the hex string may be encoded in some way, and trying to get the string this way may be wrong. This is my reason for pointing that out.