nowox
nowox

Reputation: 29106

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?

Upvotes: 0

Views: 91

Answers (2)

Cyrbil
Cyrbil

Reputation: 6478

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 :)

Upvotes: 1

bereal
bereal

Reputation: 34282

One way would be splitting it into shorts and then recombine, though it's almost equally ugly:

def pack(x):
    return struct.pack('<hh', x >> 16, x & 0xffff)

>>> pack(0x12345678).encode('hex')
'34127856'

To my knowledge there's not out-of-the-box support for mixed endianness in Python.

Upvotes: 1

Related Questions