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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短