pythonic malloc

eichin at metacarta.com eichin at metacarta.com
Mon Jul 21 20:22:53 EDT 2003


I was going to suggest struct.pack:

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

Another approach is the overpad and truncate:

   msglen = 25
   header = struct.pack("<HH", 0xf0, 2)
   msg = header + "rachel" + "\0" * msglen
   s.sendto(msg[0:msglen], addr)

ie. you know there will never be more than 25 bytes of pad (really,
more than 21, but "eww, literal numbers" presumably in your real code
you have some name attached to either the field length (which is
sufficient) in stead of the message length I've used here.)





More information about the Python-list mailing list