Python slicing | Extract “k” bits from a given position

Python Methods and Functions

Examples :

  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 ie 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 ie 8. 

We have a solution for this problem, please refer to section "Extract k bits" from a given position in a numeric reference. We can quickly fix this problem in Python using bin () and remove from it the first two characters are "0b", because the bin function prefixes "0b" as a prefix in the output binary string.

  • We need to start extracting k bits from the starting position p on the right, this means that the ending index of the extracted substrings will be end = (len (binary) — p), and the starting index will be start = end — k + 1 the original binary is a string.
  • Convert the extracted substring to decimal again.
  • # Function to extract k bits from a given one
    # position in number

     

    def extractKBits (num, k, p):

     

    # convert number to binary first

    binary = bin (num)

      

    # remove first two characters

      binary = binary [ 2 :]

     

    end = len (binary) - p

    start = end - k + 1

      

      # extract k-bit substring

    kBitSubStr = binary [start: end + 1 ]

     

    # convert the extracted substring back to decimal

      print ( int (kBitSubStr, 2 ))

     
    # Driver program

    if __ name__ = = "__ main__" :

    num = 171 < p> k = 5

    p = 2

    extractKBits (num, k, p)

     

     

    Exit :

     21 




    Tutorials