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

时间:2013-10-23 12:19:19

标签: python ctypes bit-fields

如何使用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
0b00000000000000000000001010000001

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

另一种选择可能是使用

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