Search code examples
pythonendiannesspack

How to pack in a certain order with Python


I would like to pack 0x12345678 into \x34\x12\x78\x56

I wrote this

>>> a = struct.unpack('cccc', struct.pack('I', 0x12345678))
>>> struct.pack('cccc', [a[i] for i in (1,0,3,2)])

But it is very ugly. Is there an easier way to do it?


Solution

  • Edit: Proper way: using short and reversing the endian type

    import struct
    a = struct.unpack('hh', struct.pack('I', 0x12345678))
    struct.pack('>hh', *a)
    

    Older answer
    You can reverse the usage ...

    import struct
    a1, a0, a3, a2 = struct.unpack('cccc', struct.pack('I', 0x12345678))
    struct.pack('cccc', a0, a1, a2, a3)
    

    But it's making a lot of variables

    Alternatively, swapping in the array will allow you to pass the result easier:

    import struct
    a = struct.unpack('cccc', struct.pack('I', 0x12345678))
    b = sum([[a[i+1], a[i]] for i in range(0, len(a), 2)], [])
    struct.pack('cccc', *b)
    

    Note: Their is probably a better way for swapping :)