如何使用CTYPES位字段在Python中构造32位UINT?
我想使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它是存储的小东式。
binascii.hexlify
函数将值读为一组字节,并返回这些字符的字符串。它不是将它们视为整数。如字节,值为21 43 65 87。除非您将一组字节视为多字节单元,否则不适用endianness。如果您想将值视为32位整数,请执行此操作,这将导致87654321:
Bitfield结构也有问题,即使在C中,在许多情况下,在许多情况下,在许多情况下,移动和掩盖的方式更容易:
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:
Bitfield structures are problematic, even in C. Honestly, in many cases it's way easier to shift and mask: