Extract 'k' bits from a given position in a number. - GeeksforGeeks

31 Jan, 2022
How to extract ‘k’ bits from a given position ‘p’ in a number?
Examples: 
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.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to extract k bits from a given// position.#include <bits/stdc++.h>using namespace std; // Function to extract k bits from p position// and returns the extracted value as integerint bitExtracted(int number, int k, int p){    return (((1 << k) - 1) & (number >> (p - 1)));} // Driver codeint main(){    int number = 171, k = 5, p = 2;    cout << "The extracted number is " <<            bitExtracted(number, k, p);                 return 0;} // This code is contributed by importantly
// C program to extract k bits from a given// position.#include <stdio.h> // Function to extract k bits from p position// and returns the extracted value as integerint bitExtracted(int number, int k, int p){    return (((1 << k) - 1) & (number >> (p - 1)));} // Driver codeint main(){    int number = 171, k = 5, p = 2;    printf("The extracted number is %d",               bitExtracted(number, k, p));    return 0;}
// Java program to extract k bits from a given// position. class GFG {     // Function to extract k bits from p position    // and returns the extracted value as integer    static int bitExtracted(int number, int k, int p)    {        return (((1 << k) - 1) & (number >> (p - 1)));    }      // Driver code    public static void main (String[] args) {        int number = 171, k = 5, p = 2;        System.out.println("The extracted number is "+               bitExtracted(number, k, p));    }}
# Python program to extract k bits from a given# position. # Function to extract k bits from p position# and returns the extracted value as integerdef bitExtracted(number, k, p):      return ( ((1 << k) - 1)  &  (number >> (p-1) ) ); # number is from where 'k' bits are extracted# from p positionnumber = 171k = 5p = 2print ("The extracted number is ", bitExtracted(number, k, p))
// C# program to extract k bits from a given// position.using System; class GFG {      // Function to extract k bits from p position    // and returns the extracted value as integer    static int bitExtracted(int number, int k, int p)    {        return (((1 << k) - 1) & (number >> (p - 1)));    }       // Driver code    public static void Main()    {        int number = 171, k = 5, p = 2;                 Console.WriteLine("The extracted number is "                      + bitExtracted(number, k, p));    }} //This code is contributed by Anant Agarwal.
<?php//PHP program to extract// k bits from a given// position. // Function to extract k// bits from p position// and returns the extracted// value as integerfunction bitExtracted($number, $k, $p){    return (((1 << $k) - 1) &           ($number >> ($p - 1)));}     // Driver Code    $number = 171; $k = 5; $p = 2;    echo "The extracted number is ",          bitExtracted($number, $k, $p);           // This code is contributed by Ajit?>
<script>// JavaScript program to extract k bits from a given// position. // Function to extract k bits from p position// and returns the extracted value as integerfunction bitExtracted(number, k, p){    return (((1 << k) - 1) & (number >> (p - 1)));} // Driver code     let number = 171, k = 5, p = 2;    document.write("The extracted number is ",            bitExtracted(number, k, p));  // This code is contributed by Manoj.</script>
Output : 
The extracted number is 21
 
YouTubeGeeksforGeeks502K subscribersExtract ‘k’ bits from a given position in a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_FJ6FoEc7Yk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ujjwal Aryal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.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. 
jit_t
mank1083
importantly
amartyaghoshgfg
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Bit Fields in C
Add two numbers without using arithmetic operators
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Josephus problem | Set 1 (A O(n) Solution)
C++ bitset and its application