Unpacking Nested C Structs In Python
I am trying to unpack a C struct that is handed to my Python program in binary form and includes another nested struct. The relevant part of the C header looks like this: typedef s
Solution 1:
- You
Struct
format does not match with C structure. (finalH
should be6H
) - struct.unpack(
6h
, ..) does return 6 fields. (not one with 6 elements)
So your code should looks like ..
s = struct.Struct('= B B H H 6h 6h 6h 6H')
fields = s.unpack(packet_data)
seq, _type, flags, upTimestamp = fields[:4]
x = fields[4:10]
y = fields[10:16]
z = fields[16:22]
lowTimestamp = fields[22:]
Solution 2:
You can try construct http://construct.readthedocs.io/en/latest/
import construct as cstruct
def mps_packet_header(name):
return cstruct.Struct(
name,
cstruct.UNInt8('seq'),
cstruct.UNInt8('type'),
cstruct.UNInt16('flags'),
cstruct.UNInt16('upTimestamp'),
)
mps_acc_packet_t = cstruct.Struct(
'mps_acc_packet_t',
mps_packet_header('header')
cstruct.Array(6, cstruct.NInt16('x')),
cstruct.Array(6, cstruct.NInt16('y')),
cstruct.Array(6, cstruct.NInt16('z')),
cstruct.Array(6, cstruct.UNInt16('lowTimestamp')),
)
accpacket_t = mps_acc_packet_t
...
...
packet_data = ....
packet = accpacket_t.parse(packet_data)
print(packet)
print(packet.header)
print(packet.x, packet.y, packet.z)
Post a Comment for "Unpacking Nested C Structs In Python"