Byte oriented data types in python

"Martin v. Löwis" martin at v.loewis.de
Sun Jan 25 15:25:05 EST 2009


>> I disagree. He has a format (type, length, value), with the
>> value being variable-sized. How do you do that in the struct
>> module?
> 
> You construct a format string for the "value" portion based on
> the type/length header.

Can you kindly provide example code on how to do this?

> I don't see how that can be the case.  There may not be a
> single C struct that can represent all frames, but for every
> frame you should be able to come up with a C struct that can
> represent that frame.

Sure. You would normally have a struct such as

struct TLV{
  char type;
  char length;
  char *data;
};

However, the in-memory representation of that struct is *not*
meant to be sent over the wire. In particular, the character
pointer has no meaning outside the address space, and is thus
not to be sent.

> Both.  For varible size/format stuff you decode the first few
> bytes and use them to figure out what format/layout to use for
> the next chunk of data.  It's pretty much the same thing you do
> in other languages.

In the example he gave, I would just avoid using the struct module
entirely, as it does not provide any additional value:

def encode(type, length, value):
  return chr(type)+chr(length)+value

Regards,
Martin



More information about the Python-list mailing list