Python Slicing | Extract ‘k’ bits from a given position

How to extract ‘k’ bits from a given position ‘p’ in a number?

**Examples:**

Input :number = 171 k = 5 p = 2Output :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 = 1Output :The extracted number is 8 72 is represented as 1001000 in binary, so, you should get only 01000 i.e 8.

We have existing solution for this problem please refer Extract ‘k’ bits from a given position in a number link. We can solve this problem quickly in python using slicing. Approach is simple,

- Convert given number into it’s binary using bin() function and remove first two characters ‘0b’ from it, because bin function appends ‘0b’ as prefix in output binary string.
- We need to start extracting k bits from starting position p from right, that means end index of extracted sub-string will be
**end = (len(binary) – p)**and start index will be**start = end – k + 1**of original binary string. - Convert extracted sub-string into decimal again.

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

**Output:**

21

Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. And to begin with your Machine Learning Journey, join the **Machine Learning – Basic Level Course**