How to left shift a bitarray in python

3.8k Views Asked by At

I have a bit array named c0 containing 28 bits

bitarray('1111011111111111111111110001')

how can I left shift this bit array for a number of times, meaning one left shift, two left shift, etc.? One left shift is fine for now!

NOTE: This pertains to the bitarray package.

2

There are 2 best solutions below

0
On BEST ANSWER

You could use slicing:

def leftshift(ba, count):
    return ba[count:] + (bitarray('0') * count)

def rightshift(ba, count):
    return (bitarray('0') * count) + ba[:-count]

These maintain the bit-width of the input, dropping bits on one end and padding with 0 on the other.

You can create your own subclass of the bitarray type:

class mybitarray(bitarray):
    def __lshift__(self, count):
        return self[count:] + type(self)('0') * count
    def __rshift__(self, count):
        return type(self)('0') * count + self[:-count]
    def __repr__(self):
        return "{}('{}')".format(type(self).__name__, self.to01())

Demo:

>>> c0 = mybitarray(c0)
>>> c0
mybitarray('1111011111111111111111110001')
>>> c0 << 4
mybitarray('0111111111111111111100010000')
>>> c0 >> 4
mybitarray('0000111101111111111111111111')

You can also poke the author to support these operations natively.

6
On

<< and >> are the shift operators (the bitarray class should override the __ilshift__ and __irshift__ methods.