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,nim,i,v):
mask = ~(1 << i)
return (num & mask) | (v << i)
def updateBit(self,n,m,i,j): #5-1
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
def printBinary(self,num): #5-2
if num >= 1 or num <= 0:
return "Error"
tmp_str = ""
tmp_str += "0."
while num > 0:
if len(tmp_str) >= 33:
return "Error"
r = num * 2
if r >= 1:
tmp_str += "1"
num = r - 1
else:
tmp_str+= "0"
num = r
return tmp_str
if __name__ == '__main__':
N = 1024
M = 19
i = 2
j = 6
b = Bitutils()
#5-1
#c = b.updateBit(N,M,i,j)
#print(bin(c))
#5-2
c = b.printBinary(0.75)
print(c)
c = b.printBinary(0.875)
print (c)
Est-ce que tout va bien en python lors de l'ajout de nouveaux caractères à une chaîne existante? Est-ce que cela crée une chaîne de caractères complètement nouvelle?
Recommended Posts