简体   繁体   English

如何解压 Python 中数组的样式结构 C

[英]How to unpack C Style struct of array in Python

I am using struct.unpack to unpack a C styled struct in python.我正在使用struct.unpack在 python 中解压缩 C 样式的结构。 I have a working method but was expecting to optimize and tried the not working method.我有一种工作方法,但希望优化并尝试了不工作的方法。

C Code: C 代码:

            struct __attribute__((packed))
        {
            struct
            {
                uint16_t A : 4;
                uint16_t B : 12;
            } status;

            int16_t   C;
            int16_t   D;
            int16_t   E;
            int16_t   F[4];
            float32_t G;
        } sampleStruct;

Python code: Python代码:

Working:在职的:

A, B, C, D, E, F0, F1, F2, F3, G = struct.unpack('<BHhhh4hf', bytes(rx_packet[1:]))

Not working:不工作:

A, B, C, D, E, F, G = struct.unpack('<BHhhh4hf', bytes(rx_packet[1:]))

How can I correct the not working method?如何纠正不工作的方法?

As long as there is only one array, use an extended unpacking assignment :只要只有一个数组,就使用扩展解包赋值

#              v pack into F
A, B, C, D, E, *F, G = struct.unpack('<BHhhh4hf', bytes(rx_packet[1:]))

The *F target will create a list that contains the remainder of items that could not be matched to any previous or later targets. *F目标将创建一个列表,其中包含无法与任何先前或以后的目标匹配的剩余项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM