[Tutor] converting to Ascii from hex
Fri, 8 Feb 2002 09:55:10 +0100
On 0, lonetwin <email@example.com> wrote:
> Hi everybody,
> For a program I'm working on I get data in ASCII hex digit
> characters (0-9, A-F), with two sequential ASCII hex digits corresponding
> to the hex value of each data byte. Eg: (because I know what I just said
> makes no sense :)), an ASCII "A" data character is sent as the two ASCII
> characters "41" (ie: 0x41 == 65 == ord('A')
> Now, the problem is I need to intepret this, what follows below is
> what I could hack up, but is kinda ugly. Could someone gimme
> something better ??
> intepreter session:
> >>> p ="""416268696A6565740A353435303134392870756E65290D
> ... 35353130363639286F666629"""
> >>> s = [ chr(int(p[x:x+2], 16)) for x in range(0, len(p), 2) ]
> >>> s
> ['A', 'b', 'h', 'i', 'j', 'e', 'e', 't', '\n', '5', '4', '5', '0', '1',
> '4', '9', '(', 'p', 'u', 'n', 'e', ')', '\r', '5', '5', '1', '0', '6',
> '6', '9', '(', 'o', 'f', 'f', ')']
I'd do it exactly the same way, I think.
It may be a bit ugly and unreadable, so you might want to write it in a more
verbose style, depending on taste, eg
s =  # List of characters
for location in range(0, len(p), 2):
# Convert from hex to int, then to ascii
character = chr(int(p[location:location+2], 16))
This does the same thing and is a little slower, but more readable for
anyone who isn't fluent with list comprehension style and the other
But it's mostly taste. What you have works fine.