views:

242

answers:

2

I'm trying to convert a Perl script to python, and it uses quite a few different packs. I've been able to figure out the lettering differences in the "templates" for each one, but I'm having an issue with understanding how to handle Perl's lack of length declaration.

example:

pack('Nc*',$some_integer,$long_array_of_integers);

I don't see an analog for this "*" feature in struct.pack, on Python. Any ideas on how to convert this to Python?

+1  A: 

Perl's pack is using the '*' character similar to in regular expressions--meaning a wildcard for more of the same. Here, of course, it means more signed ints.

In Python, you'd just loop through the string and concat the pieces:

result = struct.pack('>L', some_integer)
for c in long_array_of_integers:
    result += struct.pack('b',c)
ewall
+4  A: 

How about this?

struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)
abbot
I like your idea of keeping it all inside the pack() method, but I get "struct.error: pack requires exactly x arguments" and couldn't trick it into unpacking (no pun intended) the array.
ewall
@ewall: there was a small typo, fixed the code.
abbot