python 如何打包具有位字段宽度的结构?

jim*_*ing 3 c python struct

//c struct code with filed width:

    struct{
      unsigned int x:1;
      unsigned int y:25;
      unsigned int z:6;
    };
Run Code Online (Sandbox Code Playgroud)

现在我想用python重写它,打包并发送到网络,

python中的package结构体,可以打包/解包数据类型。

例如:

struct.pack('!I10s',1,'hello')
Run Code Online (Sandbox Code Playgroud)

但我不知道如何处理具有字段宽度的结构,如 c 结构示例。有人知道吗?

Shl*_*ieb 5

我意识到已经晚了,但以下内容可以帮助新手。

您可以ctypesstruct.pack_into/结合使用struct.unpack_from

import struct
import ctypes


class CStruct(ctypes.BigEndianStructure):
    _fields_ = [
        ("x", ctypes.c_uint32, 1),  # 1 bit wide
        ("y", ctypes.c_uint32, 25), # 25 bits wide
        ("z", ctypes.c_uint32, 6)   # 6 bits wide
    ]


cs = CStruct()

# then you can pack to it:
struct.pack_into('!I', cs,
                 0, # offset
                 0x80000083)
print(f'x={cs.x} y={cs.y} z={cs.z}')
# x=1 y=2 z=3

# or unpack from it:
cs_value, = struct.unpack_from('!I', cs)
print(hex(cs_value))
# 0x80000083
Run Code Online (Sandbox Code Playgroud)