unpacking pythons struct.pack in another language

128 Views Asked by At

I want to "unpack" OR de-serialize the formatted data that is outputed from python's struct.pack() function. The data is sent over the network to another platform that uses Java only.

The Python function that sends data over the network, uses this formater:

def formatOutputMsg_Array(self, mac, arr):
        mac_bin = mac.encode("ascii");
        mac_len = len(mac_bin);

        arr_bin = array.array('d', arr).tobytes();
        arr_len = len(arr_bin);

        m = struct.pack('qqd%ss%ss' % (mac_len, arr_len), mac_len, arr_len, time.time(), mac_bin, arr_bin);

        return m

Here are the docs for python's struct (refer to section 7.3.2.2. Format Characters): https://docs.python.org/2/library/struct.html

1) The issue is what does 'qqd%ss%ss' mean ???

Does it mean -> long,long,double,char,char,[],char[],char,char[],char[]

2) why is modulo "%" used here with a tuple 'qqd%ss%ss' % (mac_len, arr_len) ?

1

There are 1 best solutions below

2
On BEST ANSWER

The first argument to pack is the result of the expression 'qqd%ss%ss' % (mac_len, arr_len), where the two %s are replaced by the values of the given variables. Assuming mac_len == 8 and arr_len == 4, for example, the result is qqd8s4s. s preceded by a number simply means to copy the given bytes for that format into the result.