【问题标题】:How to get the first 11 bits of a 32 bit int with ctypes如何使用 ctypes 获取 32 位 int 的前 11 位
【发布时间】:2013-10-23 12:19:19
【问题描述】:

如何使用ctypes 获取 32 位 int 的前 11 位?

import ctypes

class Fields(ctypes.Structure):
    _pack_ = 1
    _fields_ = [('a', ctypes.c_uint, 11)]

class BitField(ctypes.Union):
    _pack_ = 1
    _fields_ = [('b', Fields),
                ('raw', ctypes.c_uint)]

bf = BitField()
bf.raw = 0b01010000001000000000000000000001

print('0b{:0>32b}'.format(bf.raw))
print('0b{:0>32b}'.format(bf.b.a))

结果:

0b01010000001000000000000000000001
0b00000000000000000000000000000001

我想要

0b01010000001000000000000000000001 0b000000000000000000000001010000001

【问题讨论】:

  • 我不清楚你想要什么。第一个输出好吗?我看不出有什么不同。
  • 第一行32位数字不变,我只是打印出来供参考。

标签: python ctypes bit-fields


【解决方案1】:

另一种选择是使用

class Fields(ctypes.Structure):
    _pack_ = 1
    _fields_ = [('x', ctypes.c_uint, 21), ('a', ctypes.c_uint, 11)]

【讨论】:

    【解决方案2】:

    位字段的实现差异很大。如果您想从整数中提取特定位(而不是与 C 库的 struct 互操作),最好完全避免使用 ctypes 并使用按位运算:

    raw = 0b01010000001000000000000000000001
    a = raw >> (32 - 11)
    

    【讨论】:

    • 这是我通常做的,但我想看看ctypes是否更快。
    猜你喜欢
    • 2021-02-05
    • 2015-08-03
    • 2011-08-14
    • 2016-09-13
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    相关资源
    最近更新 更多