How to set subset of bits in X equivalent to ones in Y ?

How to set subset of bits in X equivalent to ones in Y ?



1. Right shift X >> i
3. Run loop from 0 to j-1
2. if(!(X (lsb) ^ Y(lsb)), then continue, else X(lsb) = ~X(lsb)

def replace_bits(X, Y, i, j):
    mask = ~(2**(j+1) - 2**i)
    return (mask & X) | (Y << i)

>>> replace_bits(int('10101010', 2), int('1110', 2), 1, 4)
188
>>> bin(replace_bits(int('10101010', 2), int('1110', 2), 1, 4))
'0b10111100'

Comments

Popular posts from this blog

How to build unlimited levels menu through PHP and MySQL

How to build a map of the frequency with which characters occur in a file in OCaml?

How to create timed pop-up windows using MVVM?