Search code examples
pythonpython-2.7bit-manipulationbit-shift

Bitwise left shift in Python


I have submitted a code snippet shown below:

def shift():
    m = 8
    low = '10100111'
    lw = int(low, 2)
    lw = lw << 1
    l_bin = bin(lw)[2:].zfill(m)

Output ==> 101001110(9-bits)

while desired output ==> 01001110(8-bits)

I could understand that right shifting the lw variable causes the integer value to shift from 167 to 334. But I want the output to be the desired output.


Solution

  • You have to mask the upper bits if you want to emulate a byte (like it would behave in C):

    lw = (lw<<1) & 0xFF
    

    Of course, that is, if you keep m set to 8 or it won't work.

    If m varies, you can compute (or pre-compute) the mask value like this:

    mask_value = 2**m-1
    lw=(lw<<1) & mask_value
    

    (The aim of all this is to prefer arithmetic operations to string operations which are more CPU/memory intensive.)