Working with binary data, S-records (long)
Greg Ewing (using news.cis.dfn.de)
me at privacy.net
Thu Mar 20 22:24:55 EST 2003
Hans-Joachim Widmaier wrote:
> Whenever I play with binary data in Python, a dream of a mutable string
> data type crops up. Doing byte fiddling with strings is quite ok as long
The array module can be useful for things like this.
array.array('c') gives you an efficient mutable sequence
of chars.
> data = [int(line[i:i + 2], 16) for i in range(2, len(line), 2)]
You could replace this with something like
import struct, binascii
format = "B"*((len(line)-2)/2)
data = struct.unpack(format, binascii.unhexlify(line[2:]))
> adr = (long(data[0]) << 24) + (data[2] << 16) + (data[3] << 8) + data[4]
You could try
addr = struct.unpack(">L",
"%s%s%s%s" % (data[0], data[2], data[3], data[4]))[0]
although it's not clear whether it would be any faster.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list