我想读取 64 位数据中的位并将其放入 Register 类的相应位字段中,我不想使用位数组模块,Python 中是否有任何传统方法可以实现此目的。
我研究了这个主题,得到了以下链接——[1]:How to read bits from a file? [位字段读取链接][1]但这没有帮助,示例代码片段非常感谢。提前致谢。
class Register(object):
def __init__(self, x):
self.BitField7= 0
self.BitField6= 0
self.BitField5= 0
self.BitField4= 0
self.BitField3= 0
self.BitField2= 0
self.BitField1= 0
self.fieldwidths = (6,12,6,4,12,8,16)
self.field_names=["BitField1","BitField2","BitField3","BitField4","BitField5","BitField6","BitField7"]
obj= Register('0b11011101110111011101110111011101110011001100110011001100110011001011101110111011101110111011101110101010101010101010101010101010') # input is 0xAAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD
print obj # should print 0xAAAAAAAABBBBBBBB
提前致谢
最佳答案
以下代码会将二进制数的请求部分加载到字段中:
class Register(object):
def __init__(self,x):
self.fieldwidths = [6,12,6,4,12,8,16]
## Reverse the input string then convert it to an integer
x = int(x[2:][::-1],2)
## To keep code size down, store fields in a list (+ laziness)
## [BitField1, BitField2, ...,BitField7]
self.fields = [0,0,0,0,0,0,0]
for i,width in enumerate(self.fieldwidths):
## You can change the variables this stores the values in to
## your liking, but this is the basic procedure
## Store the last "width" number of bits in the current field
## e.g. 0b1000101 & 0b111 (or (2**3)-1) yields 0b101
self.fields[i] = x & ((2**width)-1)
## Chop off the last "width" number of bits from x
## e.g. 0b1010 >> 1 would result in 0b101
x = x >> width
obj = Register('0b11011101110111011101110111011101110011001100110011001100110011001011101110111011101110111011101110101010101010101010101010101010')
这将导致:
BitField1 = 0b111011
BitField2 = 0b111011101110
BitField3 = 0b101110
BitField4 = 0b1011
BitField5 = 0b1100111011
BitField6 = 0b110011
BitField7 = 0b11001100110011
结果可能不是您想要的,因为您提供的数据不是 64 位而是 128 位,这意味着程序将忽略输入数据的 64 个最高有效位。
编辑:
如果您只想硬编码变量名称和字段宽度,您可以扩展 for 循环并分配变量:
class Register(object):
def __init__(self,x):
## Reverse the input string then convert it to an integer
x = int(x[2:][::-1],2)
self.Bitfield1 = x & ((2**6)-1)
x = x >> 6
self.Bitfield2 = x & ((2**12)-1)
x = x >> 12
self.Bitfield3 = x & ((2**6)-1)
x = x >> 6
self.Bitfield4 = x & ((2**4)-1)
x = x >> 4
self.Bitfield5 = x & ((2**12)-1)
x = x >> 12
self.Bitfield6 = x & ((2**8)-1)
x = x >> 8
self.Bitfield7 = x & ((2**16)-1)
obj = Register('0b11011101110111011101110111011101110011001100110011001100110011001011101110111011101110111011101110101010101010101010101010101010')
关于python - 如何读取64位数据中的位放入Python中相应的位字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32129186/