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))
Il était facile de déplacer le bit et de calculer ou, Pour l'insertion, vous devez définir une fois la partie d'insertion sur 0.
Recommended Posts