Struct usage and varying sizes of h, l, etc

Dan Bishop danb_83 at yahoo.com
Wed May 21 00:55:14 EDT 2008


On May 20, 5:59 pm, Robert Kern <robert.k... at gmail.com> wrote:
> 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".

There are also minimum sizes for each type:

char: 8 bits
short: 16 bits
int: 16 bits
long: 32 bits
long long: 64 bits

> 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.

Also, according to the documentation for the struct module, the =, <,
and > format characters specify "std. size" rather than "native size".



More information about the Python-list mailing list