T T T T - 1 year ago 75
Python Question

bitwise left shift in python

I have submitted a code-snippet shown below:

def shift():

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 Source

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)