bit.py
#-*- coding:utf-8 -*-
class Bitutils():
def getBit(self,num,i):
return(num & (1 << i) !=0 )
def setBit(self,num1,i):
return (num | (1 << i))
def clearBit(self,num,i):
mask = ~(1 << i)
return num & mask
def clearBitsMSBthroughI(self,num,i):
mask = (1 << i) -1
return num & mask
def clearBitsIthrough(self,num,i):
mask = ~((1 << (i+1)) -1)
def updateBit(self,n,m,i,j):
allOnes = ~0
left = allOnes << (j + 1)
right = ((1<<i) - 1)
mask = left|right
n_cleared = n & mask
m_shifted = m << i
return n_cleared | m_shifted
if __name__ == '__main__':
N = 1024
M = 19
i = 2
j = 6
b = Bitutils()
c = b.updateBit(N,M,i,j)
print(bin(c))
Bit shift and or operation was easy, but For insertion, you have to set the insertion part to 0 once.