Bhaskar vedula
Bhaskar vedula

Reputation: 93

Bit manipulate clarification in Python

Hi I'm referring to following link How do I manipulate bits in Python? If I execute the last responded answer code I get below error. Here is the code snippet for quick reference

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] 

After fixing error(2L change to 2**) in the above code I get below error

When I try to execute the above code I get following error Traceback (most recent call last): File "BitVector.py", line 20, in b[3:0] = 0xD TypeError: 'BitVector' object does not support item assignment

Upvotes: 1

Views: 120

Answers (1)

unutbu
unutbu

Reputation: 880907

__setslice__ and __getslice__ have been deprecated since Python2.6 and removed in Python3.5. Use __setitem__ and __getitem__ instead:

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])

prints

D
E
A
D

Upvotes: 1

Related Questions