How to extract ‘k’ bits from a given position ‘p’ in a number?
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.
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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Extract 'k' bits from a given position in a number.
- Python | K elements Slicing
- String Slicing in Python
- Python List Comprehension and Slicing
- Python | Reverse Slicing of given string
- Python | Variable list slicing
- Python | Custom slicing in List
- Python | Custom List slicing Sum
- Slicing range() function in Python
- Python | Reverse Incremental String Slicing
- Python | Reverse Interval Slicing String
- Python | Get the substring from given string using list slicing
- Interesting facts about strings in Python | Set 2 (Slicing)
- Python | Alternate range slicing in list
- Python Slicing | Reverse an array in groups of given size
- Basic Slicing and Advanced Indexing in NumPy Python
- Program to cyclically rotate an array by one in Python | List Slicing
- Python | Extract suffix after K
- numpy.extract() in Python
- Python | Extract characters except of K string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.