Python ctype位字段:获取位字段位置
我创建了一个ctype位域结构,它具有相应的并集,可以通过单个位域和整数值访问它。 我可以使用包含字段名称的变量设置单个字段,但现在我想知道特定字段属于哪个字节。 下面是我的代码示例:Python ctype位字段:获取位字段位置,python,ctypes,bit-fields,Python,Ctypes,Bit Fields,我创建了一个ctype位域结构,它具有相应的并集,可以通过单个位域和整数值访问它。 我可以使用包含字段名称的变量设置单个字段,但现在我想知道特定字段属于哪个字节。 下面是我的代码示例: import ctypes c_short = ctypes.c_uint16 class Flags_bits(ctypes.LittleEndianStructure): _fields_ = [ ("bitField1", c_short, 1), ("bitFi
import ctypes
c_short = ctypes.c_uint16
class Flags_bits(ctypes.LittleEndianStructure):
_fields_ = [
("bitField1", c_short, 1),
("bitField2", c_short, 4),
("bitField3", c_short, 6),
("bitField4", c_short, 1),
("bitField5", c_short, 2),
("bitField6", c_short, 2),
("bitField7", c_short, 6),
("bitField8", c_short, 4),
("bitField9", c_short, 4),
("bitField10", c_short, 1),
("bitField11", c_short, 1)]
class Flags(ctypes.Union):
_fields_ = [("b", Flags_bits),
("asInt", c_short*6)]
def setFlag (flagName, value):
flags = Flags()
setattr(flags.b, flagName, value)
print getattr(flags.b, flagName)
现在我想知道的是我的标志属于哪个整数(即,属于哪个flags.asInt[I]),我在寻找一种“get_location”属性来获取结构中的标志位置,并从中检索整数的“I”索引,但我找不到任何东西
有没有一个简单的方法可以做到这一点
提前感谢您的回复 结构中的每个字段描述符都有一个定义其存储单元字节偏移量的
偏移量
属性。它还有一个size
属性,其含义取决于它是否是位字段。如果是位字段,则size
的低位字包含字段的存储单元位偏移量,高位字包含字段中的位数。否则,size
是以字节为单位的字段大小
由于您的位字段存储单元都是c\u short
,您只需将字段的字节偏移量
除以sizeof(c\u short)
即可计算出asInt
中的相应项。例如,标志\u bits.bitfield 6.offset//2==0
和标志\u bits.bitfield 7.offset//2==1
还可以计算每个字段的位范围:
import ctypes
c_short = ctypes.c_cshort
class Flags_bits(ctypes.LittleEndianStructure):
_fields_ = [("bitField1", c_short, 1),
("bitField2", c_short, 4),
("bitField3", c_short, 6),
("bitField4", c_short, 1),
("bitField5", c_short, 2),
("bitField6", c_short, 2),
("bitField7", c_short, 6),
("bitField8", c_short, 4),
("bitField9", c_short, 4),
("bitField10", c_short, 1),
("bitField11", c_short, 1)]
for field_descr in Flags_bits._fields_:
name = field_descr[0]
field = getattr(Flags_bits, name)
bfield_bits = field.size >> 16
if bfield_bits:
start = 8 * field.offset + field.size & 0xFFFF
stop = start + bfield_bits
else:
start = 8 * field.offset
stop = start + 8 * field.size
print("{:>10s}: bits {:>2d}:{:>2d}".format(
name, start, stop))
输出:
bitField1:位0:1
位字段2:位1:5
位字段3:位5:11
位字段4:位11:12
位字段5:位12:14
位字段6:位14:16
位字段7:位16:22
位字段8:位22:26
位字段9:位26:30
位字段10:位30:31
位字段11:位31:32
谢谢,这很有帮助!然而,在我的机器中(我在窗口机器上运行Python2.7.2),我不得不将“*”改为“,”以避免收到投诉。但还是很好的回答。@eryksun:谢谢你的回答!你能告诉我关于位域大小和偏移量的问题是否可以在文档中找到吗?我在那里找不到它…@maggie,文档简要地提到了字段描述符类型,但属性没有记录。这只会留下源,例如。