Python 程式從給定位置提取“k”位的程式?
此函式用於從位置 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP