此函数用于从pos位置提取k位并返回提取的值。在这里,我们使用python切片技术。
Input:: number=170 K=5 Pos=2 Output=21
Extractionbit(no,k,pos) /*user input number is stored in variable no, extracted bit is stored in variable k and the position of bit is pos. */ Step 1 : first convert the number into its binary form using bin(). Step 2 : remove the first two character. Step 3 : then extracting k bits from starting position pos from right.so, the ending index of the extracting substring is e=len(bi)-pos and starting index=e-k+1 Step 4 : extract k bit sub-string. Step 5 : convert extracted sub-string into decimal again.
# python program to extract ‘k’ bits from a given position in a number def extractedbits(no,k,pos): bi = bin(no) bi = bi[2:] e = len(bi) - pos s = e - k + 1 substr = bi[s : e+1] print ("FINAL RESULT ::>",int(substr,2)) # Driver program if __name__ == "__main__": no=int(input("Enter number ::>")) k = int(input("Enter k bit's ::>")) pos = int(input("Enter position ::>")) extractedbits(no,k,pos)
输出结果
Enter number ::>170 Enter k bit's ::>5 Enter position ::>2 FINAL RESULT ::>21