您好,我指的是以下链接 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 (most最近的调用最后): File "BitVector.py", line 20, in b[3:0] = 0xD TypeError: 'BitVector' object does not支持项目分配
最佳答案
自 Python2.6 和 removed in Python3.5 起,
__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
关于python - Python 中的位操作说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804054/