Peter Chuang
Peter Chuang

Reputation: 94

How to struct.pack() a variable length list in Python

For example when len(args) = 2:

args = []
args.append('arg1')
args.append('argument2')

bytes = struct.pack('B' * len(args), len(args[0]), len(args[1]))

However, I need to handle variable-length args, that is, len(args) = n, where n is any positive integer.

Upvotes: 0

Views: 2005

Answers (2)

dstromberg
dstromberg

Reputation: 7167

You probably should add a length field to your output, so you know how many things to read back in. Or rather use a "number of strings" followed by "length of string1", "length of string2", ..., "length of stringn".

Upvotes: 0

emesday
emesday

Reputation: 6186

Try:

bytes = struct.pack('B' * len(args), *[len(x) for x in args])

To unpack this:

struct.unpack('B' * len(bytes), bytes)

Because 'B' means 1-byte unsigned char, len(bytes) can be length of it.

Upvotes: 3

Related Questions