T T T T - 3 months ago 12
Python Question

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 causes the integer value to shift from 167 to 334. But I want the output to be desired output.

Answer

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 opertations which are more CPU/memory intensive)