📌  相关文章
📜  Python切片|从给定位置提取’k’位

📅  最后修改于: 2021-05-06 22:32:08             🧑  作者: Mango

如何从数字中给定位置“ p”中提取“ k”位?

例子:

Input : number = 171
             k = 5 
             p = 2
Output : The extracted number is 21
171 is represented as 10101011 in binary,
so, you should get only 10101 i.e. 21.

Input : number = 72
            k = 5 
            p = 1
Output : The extracted number is 8
72 is represented as 1001000 in binary,
so, you should get only 01000 i.e 8.

我们已有解决此问题的方法,请参阅从数字链接中给定位置提取“ k”位。我们可以在Python使用切片快速解决此问题。方法很简单,

  1. 使用bin()函数将给定数字转换为二进制数,并从中删除前两个字符’0b’,因为bin函数将’0b’作为前缀附加在输出二进制字符串。
  2. 我们需要从右边的起始位置p开始提取k位,这意味着提取的子字符串的结束索引将为end =(len(binary)– p),而开始索引将为start = end – k + 1原始二进制字符串。
  3. 再次将提取的子字符串转换为十进制。
# Function to extract ‘k’ bits from a given
# position in a number
  
def extractKBits(num,k,p):
  
     # convert number into binary first
     binary = bin(num)
  
     # remove first two characters
     binary = binary[2:]
  
     end = len(binary) - p
     start = end - k + 1
  
     # extract k  bit sub-string
     kBitSubStr = binary[start : end+1]
  
     # convert extracted sub-string into decimal again
     print (int(kBitSubStr,2))
  
# Driver program
if __name__ == "__main__":
    num = 171
    k = 5
    p = 2
    extractKBits(num,k,p)
  
      

输出:

21