Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 615
Valdemarick Avatar asked Oct 06 '09 19:10

Valdemarick


People also ask

What is struct pack in Python?

struct. pack() is the function that converts a given list of values into their corresponding string representation. It requires the user to specify the format and order of the values that need to be converted. The following code shows how to pack some given data into its binary form using the module's struct.

What does struct unpack do Python?

Python struct pack_into(), unpack_from() These functions allow us to pack the values into string buffer and unpack from a string buffer. These functions are introduced in version 2.5. That's all for a short introduction of python struct module.


2 Answers

How about this?

struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)
like image 148
abbot Avatar answered Sep 18 '22 17:09

abbot


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)
like image 34
ewall Avatar answered Sep 20 '22 17:09

ewall