如何使用CTYPES位字段在Python中构造32位UINT?

发布于 2025-01-31 04:50:52 字数 756 浏览 3 评论 0原文

我想使用python3 ctypes位字段构造一个未签名的32位int,如下所示:

c_uint = ctypes.c_uint32

class Flags_bits(ctypes.LittleEndianStructure):
    _fields_ = [ 
            ("a", c_uint, 4),
            ("b", c_uint, 4),
            ("c", c_uint, 4),
            ("d", c_uint, 4),
            ("e", c_uint, 4),
            ("f", c_uint, 4),
            ("g", c_uint, 4),
            ("h", c_uint, 4)]

当我用特定的整数替换flags_bits将其替换为特定整数值时,

aa = Flags_bits(1,2,3,4,5,6,7,8)
print(hexlify(aa).decode('utf-8'))

输出是

21436587

我所期望的,

87654321 # binary of 1000 0111 0110 0101 0100 0011 0010 0001

因为很小的endian构造,位从低位开始。如何获得预期的输出?我做错了吗?有人可以帮我吗?提前致谢!

I would like to construct an unsigned 32-bit int using Python3 ctypes bit field, as follows:

c_uint = ctypes.c_uint32

class Flags_bits(ctypes.LittleEndianStructure):
    _fields_ = [ 
            ("a", c_uint, 4),
            ("b", c_uint, 4),
            ("c", c_uint, 4),
            ("d", c_uint, 4),
            ("e", c_uint, 4),
            ("f", c_uint, 4),
            ("g", c_uint, 4),
            ("h", c_uint, 4)]

When I substitute Flags_bits with specific integer values,

aa = Flags_bits(1,2,3,4,5,6,7,8)
print(hexlify(aa).decode('utf-8'))

The output is

21436587

I was expecting an output like

87654321 # binary of 1000 0111 0110 0101 0100 0011 0010 0001

Since Little-endian constructs bits starting with the low bit. How can I obtain the expected output? Is there anything I did wrong? Could someone be so kind to help me? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潜移默化 2025-02-07 04:50:52

它是存储的小东式。 binascii.hexlify函数将值读为一组字节,并返回这些字符的字符串。它不是将它们视为整数。如字节,值为21 43 65 87。除非您将一组字节视为多字节单元,否则不适用endianness。

如果您想将值视为32位整数,请执行此操作,这将导致87654321:

import struct
...
aa = Flags_bits(1,2,3,4,5,6,7,8)
aa_int = struct.unpack('I',aa)[0]
print(hex(aa_int))

Bitfield结构也有问题,即使在C中,在许多情况下,在许多情况下,在许多情况下,移动和掩盖的方式更容易:

def Flags_bits(*data):
    val = 0
    for n in reversed(data):
        val = (val << 4) | n
    return val

It IS stored little-endian. The binascii.hexlify function reads the value as a set of bytes, and returns a string of those bytes. It's not treating them as an integer. As bytes, the values are 21 43 65 87. Unless you treat a set of bytes as a multi-byte unit, endianness does not apply.

If you want to see the value as a 32-bit integer, do this, which results in 87654321:

import struct
...
aa = Flags_bits(1,2,3,4,5,6,7,8)
aa_int = struct.unpack('I',aa)[0]
print(hex(aa_int))

Bitfield structures are problematic, even in C. Honestly, in many cases it's way easier to shift and mask:

def Flags_bits(*data):
    val = 0
    for n in reversed(data):
        val = (val << 4) | n
    return val
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文