python - Python 中的位操作说明

标签 python python-3.5

您好,我指的是以下链接 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/

相关文章:

python - numpy 逻辑中首次出现

windows-10 - 安装 glove-python-> link.exe 时出错,退出状态为 1181

python - 如何编写一个接受 int 或 float 的 C 函数?

python - 根据查找函数标准拼接数据框中的整个列

python - Python的协程类型是在哪里定义的?

python - 如何在不卸载的情况下解决导入cv2上的ImportError

redis - Celery 尝试从 Redis 队列中读取结果时出现 Unicode 解码错误

python - Optional[Type[Foo]] 在 Python 3.5.2 中引发 TypeError

Python PEP 8 : Blank lines at the beginning of a module

python - 从 pickle 文件加载 multiprocessing.manager.dictionary 时出错