struct module...
Tim Peters
tim.one at comcast.net
Fri Mar 21 11:04:26 EST 2003
[Franck Bui-Huu]
> I'm trying to read from a binary file data.
> These data have been written by a C soft using structure like
> struct xxx {
> u1 length;
> u1 array[length];
> }
Picturing a struct isn't really helpful here, in part because C structs
don't have variable length. How the file was actually written should
suggest how to read it back in. I don't know what "u1" means here, but
assuming length is an int and array is full of doubles, and the data was
written in big-endian ("network") order and without pad bytes, this kind of
reading code is likely appropriate:
data = f.read(4)
if len(data) != 4:
raise SomeException
n = struct.unpack(">i", data)[0]
data = f.read(8*n)
if len(data) != 8*n:
raise SomeException
array = struct.unpack(">%dd" % n, data)
OTOH, if u1 here means unsigned byte, life would be easier if you skipped
the struct module:
data = f.read(1)
if len(data) != 1:
raise SomeException
n = ord(data)
data = f.read(n)
if len(data) != n:
raise SomeException
array = map(ord, data)
> ...
> did someone extend struct module to manage not fixed lengh of
> array. We could imagine a format for struct xxx like:
> 'B?(1)c' where ?(1) means the value of the first unpcked data.
Doesn't seem worth the confusion or bother to me.
More information about the Python-list
mailing list