Question about struct.unpack
Scott David Daniels
scott.daniels at acm.org
Wed Feb 22 12:23:12 EST 2006
Eric Jacoboni wrote:
> Hi,
>
> To experiment with unpacking, i've written a little C code which
> stores one record in a file. Then, i try to reread this file to unpack
> the record.
>
> Here's the struct of a record:
>
> typedef struct {
> char nom[30];
> double taille;
> int age;
> char plop;
> } enreg_t;
>
> The whole size, as given by sizeof() is 48, due to byte alignment.
> ...i've tried "32sdicxxx" to reach the 48 expected... Now it works...
>
> The same file, re-read with a Ruby script needs a
> str.unpack("Z32dIc").
>
> So, i don't know why i need to pad the format string in Python. Any
> clue?
>
> BTW: how to get rid of all this stuff after the \0 in the first field
> in Python? (Ruby has Z and A, but it seems that the Python 's'
> specifier is like 'A' and there is no 'Z' equivalent)
OK, the correct translation of your format is: '30sdic' (size 45) or
'30sdic3x' if you are passing the entire 48-char block. The reason
it is not size 48 is that '30sdicc' (size 46) in C takes no more room.
the alignment to the end shows up in a C sizeof.
data = struct.pack('30sdic', 'John Q. Public', 57123.25, 43, 'M')
nomz, taille, age, plop = struct.unpack('30sdic', data)
nom = nomz.rstrip('\0')
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list