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