pythonic malloc

Brad Hards bhards at bigpond.net.au
Tue Jul 22 08:19:43 EDT 2003


eichin at metacarta.com wrote:

> 
>>>> import struct
>>>> struct.pack("<HH21s", 0xf0, 2, "rachel")
>
'\xf0\x00\x02\x00rachel\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
> 
> but it is, umm, "kind of perlish" - note also that the "21s" is
> basically "string of up to 21 chars, pad with NUL if we run out" which
> is probably what you wanted, but is saying it another way.
This is nice, because it also deals with the case where the hostname would
otherwise overflow. It also matches my mental model - this isn't really a
string, its really a fixed length binary structure. Note that I don't
really know what it is - I'm trying to figure out a proprietary network
protocol.

Now I just have a question about portability. Will this break on a
big-endian box? That is, does:
struct.pack("<HH", 0xf0, 0x02)
produce:
'\x00\xf0\x00\x02'?

Would I be better off using "BBBB 21s" or "L 21s" as the format?

Brad





More information about the Python-list mailing list