Python program to extract ‘k’ bits from a given position?


This function is use to extract k bits from pos position and returns the extracted value. Here we use python slicing technique.

Example

Input:: number=170
   K=5
   Pos=2   
Output=21

Algorithm

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.

Example code

# 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) 

Output

Enter number ::>170
Enter k bit's ::>5
Enter position ::>2
FINAL RESULT ::>21

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements