2016-03-04 76 views
1

嗨我指的是以下链接 How do I manipulate bits in Python? 如果我执行最后回应的答案代码,我得到以下错误。 这里是为快速参考位操纵在Python中澄清

import math 
class BitVector: 
     def __init__(self,val): 
     self._val = val 

     def __setslice__(self,highIndx,lowIndx,newVal): 
     assert math.ceil(math.log(newVal)/math.log(2)) <= (highIndx-lowIndx+1) 

     # clear out bit slice 
     clean_mask = (2**(highIndx+1)-1)^(2**(lowIndx)-1) 

     self._val = self._val^(self._val & clean_mask) 
     # set new value 
     self._val = self._val | (newVal<<lowIndx) 
    def __getslice__(self,highIndx,lowIndx): 
     return (self._val>>lowIndx)&(2L**(highIndx-lowIndx+1)-1) ## Error in the code I think it is not 2L. 
b = BitVector(0) 
b[3:0] = 0xD 
b[7:4] = 0xE 
b[11:8] = 0xA 
b[15:12] = 0xD 

for i in xrange(0,16,4): 
    print '%X'%b[i+3:i] 

代码段在上述码错误(2L变化至2 **)固定之后我得到以下错误

当我尝试执行我获得以下上面的代码错误回溯(最近最后一次调用):文件“BitVector.py”,第20行,在b [3:0] =为0xD类型错误:“位向量”对象不支持项目分配

+0

你说你“固定”的部分实际上看起来不错,至少对Python 2中,和您发布的错误信息看起来并不像它与你发布的任何代码有关。 – user2357112

+0

您使用的是什么Python版本?该代码对我来说工作正常,直接将其复制并粘贴到Python 2.7中。删除** L **后,它仍然有效。 – Prune

+0

现在,请更正发布。这个问题应该是独立的。提供完整的代码以重现问题以及整个错误消息。 – Prune

回答

1

__setslice____getslice__以来已弃用Python2.6和removed in Python3.5。 使用__setitem____getitem__代替:

import math 

class BitVector: 
    """ 
    http://stackoverflow.com/a/150411/190597 (Ross Rogers) 
    Updated for Python3 
    """ 
    def __init__(self, val): 
     self._val = val 

    def __setitem__(self, item, newVal): 
     highIndx, lowIndx = item.start, item.stop 
     assert math.ceil(
      math.log(newVal)/math.log(2)) <= (highIndx - lowIndx + 1) 

     # clear out bit slice 
     clean_mask = (2 ** (highIndx + 1) - 1)^(2 ** (lowIndx) - 1) 

     self._val = self._val^(self._val & clean_mask) 
     # set new value 
     self._val = self._val | (newVal << lowIndx) 

    def __getitem__(self, item): 
     highIndx, lowIndx = item.start, item.stop 
     return (self._val >> lowIndx) & (2 ** (highIndx - lowIndx + 1) - 1) 

b = BitVector(0) 
b[3:0] = 0xD 
b[7:4] = 0xE 
b[11:8] = 0xA 
b[15:12] = 0xD 

for i in range(0, 16, 4): 
    print('%X' % b[i + 3:i]) 

打印

D 
E 
A 
D 
+0

谢谢,现在它工作。看起来像xrange在Python3.5中已被弃用我已经将xrange更改为范围,并且它工作正常。 –

+0

感谢您的更正。是的,在Python3中'xrange'也被删除,并且'print'被作为函数而不是语句(因此需要括号来调用函数)。 – unutbu