How do I convert Perl's pack 'Nc*' format to struct.pack for Python?
Asked Answered
I

2

5

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?

Intimidate answered 6/10, 2009 at 19:18 Comment(0)
W
7

How about this?

struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)
Word answered 6/10, 2009 at 19:39 Comment(1)
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.Terrel
T
1

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)
Terrel answered 6/10, 2009 at 19:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.