Search code examples
pythonpython-3.xstructendiannesspack

Using big endian in struct pack Python with a Pointer


I'm using the struct pack in Python 3.7.
I have this header containing 6 uint32 and one void * argument.

I want to put it in binary format. Unfortunately the interface I'm working on only supports big endian.So I actually need to transform what I send. But since P format can't have its endianess modified I always get struct error. So how can I rewrite this to avoid having this error.

PS: I cannot remove the void * it an mandatory field of my header

u1 = 0x4569 
u2 = 0x1236 
u3 = 0x4411 
u4 = 0x1236 
u5 = 0x9696 
point = 0 #(For now) 
data = 0x26358974 
buffer = struct.pack('5IPI',u1,u2,u3,u4,u5,point,data) 

Actual output

buffer = b'\x69\x45\x00\x00\x36\x12\x00\x00\x11\x44\\x00\x00\x36\x12\x00\x00\x96\x96\\x00\x00\x00\x00\x00\x00\x74\x89\x35\26' 

WHILE what I want would be:

buffer = b'\x00\x00\45\x69\x00\x00\x12\36\x00\x00\x44\x11\x00\x00\x12\x36\\x00\x00\x96\x96\x00\x00\x00\x00\x26\x35\x89\x74'

Solution

  • You may need to do this in two stages:

    u1=1
    u2=2
    u3=3
    u4=4
    u5=5
    point=6
    data=7
    
    # construct two separate buffers
    b1 = struct.pack('>5I', u1, u2, u3, u4, u5)
    b2 = struct.pack('P', point)
    

    Then convert the pointer back to a regular uint, and then back to a pointer:

    p2 = struct.unpack('I', b2)
    b2a = struct.pack('>I', p2[0])
    b1 = b1 + b2a
    print(b1)
    

    Output:

    b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06'