Search code examples
pythonpack

Pack a list with string and int type use struct.pack python


Sorry for my english

I have a list like:

[['string type','short int type','long int type','string type','float'],
['Stackoverflow','32','0','any stringgg','55.0'],
['anystring','16','1654657987984','striiingg','2.5']]

I call:

['string type','short int type','long int type','string type','float']

is the first sub-list and

['Stackoverflow','32','0','any stringgg','55.0']

is the second sub-list, same for the three sub-list

How can I use struct.pack() data in the second & third sub-lists based on the type of the first sub-list?


Solution

  • You could do something like this (quickly coded, could use some work)

    import struct
    
    type_map = {
            'string type': 's',
            'short int type': 'h',
            'long int type': 'q',
            'float': 'f'
            }
    
    conversion = {
            's': str,
            'h': int,
            'q': int,
            'f': float
            }
    
    
    def do_pack(types, data):
        if len(types) != len(data):
            raise Excpetion("wrong lengths")
        packing = '<'
        data_iter = []
        for i, struct_type in enumerate(types):
            t = type_map[struct_type]
            if t == 's':
                packing += '%ds' % len(data[i]) 
                data_iter.append(data[i])
            else:
                packing += t
                data_iter.append(conversion[t](data[i]))
        return struct.pack(packing, *data_iter), packing
    
    packer = [['string type','short int type','long int type','string type','float'],['Stackoverflow','32','0','any stringgg','55.0'],['anystring','16','1654657987984','striiingg','2.5']]
    
    types = packer[0]
    for data_set in packer[1:]:
        binary, packing = do_pack(types, data_set)
        print struct.unpack(packing, binary)
    

    OUTPUT

    ('Stackoverflow', 32, 0, 'any stringgg', 55.0)
    ('anystring', 16, 1654657987984, 'striiingg', 2.5)