[Tutor] Need help with structure unpacking module
alan.gauld at btinternet.com
Tue Mar 18 22:39:47 CET 2008
CCing the list.
Please use Reply All when responding.
> I am still little confused since I was under the impression,
> that if a c program was able to write this binary code,
> then if we know how c "packed" the data/string then
> we able to decode/unpack it using python.
Thats correct but you have to specify the correct decode
string to match what C wrote.
> Does python not know how c packs the strings?
Python knows nothing about what C does its up to the
programmer to tell Python how to interpret binary data.
So its the programmer who must know how C stores
> Please help me understand as to why unpack works
> for numbers but not for strings.
It does work for strings as both Luke and I demonstrated.
But you have to tell Python how long the string is. You
only specified 's' so Python looked for a single byte string.
You needed to specify '4s' for a 4 byte string.
Let me put it this way:
When you call decode you supply a pattern which struct
uses to determine how many bytes it needs and how to
assign those bytes to Pyhon data types Python and struct
have no idea how those bytes got there they simply take
the sequence of bytes and try to interpret them in the
way indicated by the format string.
Thus if you write an integer into a binary file you will write
4 bytes. Knowing that you can tell struct to decode that
as an integer. But you could equally well tell struct to
decode those same bytes as 4 characters and struct
will do so, because thats what you asked for. The
4 characters will be the ASCII characters with the values
of the 4 bytes making up the original number.
So the onus is on you, the programmer, to know what
the correct decode pattern is for each sequence of bytes
read. You can find out what that pattern is and how many
bytes it equates to by using things like len(), ord(), hex() etc
Youcan see an example of that in my File Handling topic
in my tutorial. Look at the section on struct.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor