您好,我指的是以下链接 How do I manipulate bits in 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 **)后,我得到以下错误
当我尝试执行上面的代码时,我得到以下错误Traceback(最近一次调用last):File&#34; BitVector.py&#34;,第20行,b [3:0] = 0xD TypeError:& #39;位向量&#39;对象不支持项目分配
答案 0 :(得分:1)
__setslice__
和__getslice__
已被弃用。
请改用__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