【问题标题】:python how to pack struct with bit field width?python如何用位域宽度打包结构?
【发布时间】:2016-12-21 06:08:13
【问题描述】:
//c struct code with filed width:

    struct{
      unsigned int x:1;
      unsigned int y:25;
      unsigned int z:6;
    };

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

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

如:

struct.pack('!I10s',1,'hello')

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

【问题讨论】:

标签: python c struct


【解决方案1】:

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

您可以将ctypes 与struct.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多