64位数据中的读取位如何放入python中的相应位域

时间:2015-08-20 22:05:47

标签: python bit-manipulation byte bit

我想读取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

提前致谢

1 个答案:

答案 0 :(得分:1)

以下代码将二进制数的请求部分加载到字段中:

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个最高有效位。 / p>

编辑:

如果您只想对变量名称和字段宽度进行硬编码,可以只展开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')