0

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.

1
  • 1
    I think the module was designed for a C-like definition of struct, which never changes size. Commented Apr 14, 2014 at 1:17

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is more about how to unpack this again.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.