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))
Es war einfach, das Bit zu verschieben und zu berechnen oder, Zum Einfügen müssen Sie den Einfügeteil einmal auf 0 setzen.
Recommended Posts