[Tutor] converting to Ascii from hex [writing a group()
Fri, 8 Feb 2002 01:19:10 -0800 (PST)
On Fri, 8 Feb 2002, lonetwin wrote:
> 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')
Interesting! Ok, let's take a look at the program:
> >>> 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', ')']
This looks good. If we want, we can write a few functions to tease out
some of the functionality. A large part of the program appears to try
grouping pairs of elements in the sequence. We can generalize the grouping
by writing a function like this:
def group(seq, n=2):
"""Given a sequence 'seq', returns a list that clumps up
'n' adjacent elements together. By default, n=2."""
pieces = 
for i in range(len(seq) / n):
pieces.append(seq[i*n : (i+1)*n])
Here's an example of group() in action:
['12', '34', '56', '78', '90']
>>> group("1234567890", 3)
['123', '456', '789']
>>> group("1234567890", 4)
Cool, so that works. Once we have something like group(), we can write
s = [ chr(int(p[x:x+2], 16)) for x in range(0, len(p), 2) ]
s = [ chr(int(chunk, 16)) for chunk in group(p)]
I think having the group() function is worth the effort, as defining 's'
becomes much nicer looking. It also gives us some versatility, because we
can easily fiddle with this to group four letters at a time.
I hope this helps!