简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM