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 0101011 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.
1) Right shift number by p-1.
2) Do bit wise AND of k set bits with the modified number. We can get k set bits by doing (1 << k) – 1.
The extracted number is 21
This article is contributed by Ujjwal Aryal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Write an Efficient Method to Check if a Number is Multiple of 3
- Position of rightmost set bit
- Find the Number Occurring Odd Number of Times
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Compute modulus division by a power-of-2-number
- Find whether a given number is a power of 4 or not
- Add 1 to a given number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Binary representation of a given number
Improved By : jit_t