Struct usage and varying sizes of h, l, etc
Robert Kern
robert.kern at gmail.com
Tue May 20 18:59:30 EDT 2008
Ethan Furman wrote:
> Greetings,
>
> I'm looking at the struct module for binary packing of ints and floats.
> The documentation refers to C datatypes. It's been many years since I
> looked at C, but I seem to remember that the data type sizes were not
> fixed -- for example, an int might be two byes on one machine, and four
> bytes on the next. Can any C programmers verify this? If it is true,
> does that mean that struct.pack('h', 8001) might give me different
> results depending on the machine it's running on?
Right. I believe (but could be wrong) that "char" is defined to be one byte, but
that "short", "int", "long", and "long long" are defined as "at least as big as
the previous type".
In practice, though, on nearly every machine that Python runs on, "char" is one
byte, "short" is two bytes, and "int" is four bytes. "longs" and "long longs"
tend to vary substantially, though; never assume sizes for them.
Single-precision floats are always four bytes and double-precision floats are
always eight bytes. "long doubles" vary; they could be twelve bytes or sixteen.
If you want to deal with fixed sizes, use struct.calcsize() to test the sizes of
each of the integer types, assign them to width-specific aliases, and always use
these aliases.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list