Extract data from ASCII file
Anton Vredegoor
anton at vredegoor.doge.nl
Mon Feb 23 06:05:49 EST 2004
eley_greg at bah.com (eleyg) wrote:
>> :10000000E7280530AC00A530AD00AD0B0528AC0BE2
>>
>> The data I want to extract are 8 hexadecimal strings, the first of
>> which is E728, like this:
>>
>> :10000000 E728 0530 AC00 A530 AD00 AD0B 0528 AC0B E2
>>
>> Also, the bytes in the string are reversed. The E728 needs to be 28E7,
>> 0530 needs to be 3005 and so on.
>
>The first response only works with python-2.3 (yield is a newly
>reserved word).
>
>The second response did not work for me and left off the last couple
>values.
The third response uses typechecking and stores a value in an
unreachable place ...
Maybe the feachur-less code is better (tested very lightly):
def asBytes(line,offset):
""" split a line into 2-char chunks, starting at offset'"""
res = []
for i in range(offset,len(line),2):
res.append(line[i:i+2])
return res
def asWords(line,offset=0,swapbytes=0):
"""split a line into words that have maximally 4 chars,
starting at offset, optionally swapping 2-char chunks"""
res = []
flip = 0
for b in asBytes(line,offset):
if flip:
if swapbytes:
res.append(b+prev)
else:
res.append(prev+b)
else:
prev = b
flip = 1-flip
if flip:
res.append(b)
return res
def test():
line =":10000000E7280530AC00A530AD00AD0B0528AC0BE2"
print asWords(line,offset=9,swapbytes=1)
if __name__=='__main__':
test()
output is:
['28E7', '3005', '00AC', '30A5', '00AD', '0BAD', '2805', '0BAC', 'E2']
Anton
More information about the Python-list
mailing list