The Wayback Machine - https://web.archive.org/web/20240718084001/https://www.geeksforgeeks.org/extract-k-bits-given-position-number/
Open In App

Extract ‘k’ bits from a given position in a number.

Last Updated : 31 Jul, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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 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.
 

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++ 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 integer
int bitExtracted(int number, int k, int p)
{
    return (((1 << k) - 1) & (number >> (p - 1)));
}
 
// Driver code
int 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




// 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 integer
int bitExtracted(int number, int k, int p)
{
    return (((1 << k) - 1) & (number >> (p - 1)));
}
 
// Driver code
int main()
{
    int number = 171, k = 5, p = 2;
    printf("The extracted number is %d",
               bitExtracted(number, k, p));
    return 0;
}


Java




// 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));
    }
}


Python3




# Python program to extract k bits from a given
# position.
 
# Function to extract k bits from p position
# and returns the extracted value as integer
def bitExtracted(number, k, p):  
    return ( ((1 << k) - 1)  &  (number >> (p-1) ) );
 
# number is from where 'k' bits are extracted
# from p position
number = 171
k = 5
p = 2
print ("The extracted number is ", bitExtracted(number, k, p))


C#




// 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
//PHP program to extract
// k bits from a given
// position.
 
// Function to extract k
// bits from p position
// and returns the extracted
// value as integer
function 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
?>


Javascript




<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 integer
function 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

Time Complexity: O(1)

Auxiliary Space: O(1)
 

 



Similar Reads

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 = 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 o
4 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n &gt; 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -&gt; 00111, again flipping 1'st and 2'nd bit -&gt; 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Difference between sums of odd position and even position nodes for each level of a Binary Tree
Given a Binary Tree, the task is to find the absolute difference between the sums of odd and even positioned nodes. A node is said to be odd and even positioned if its position in the current level is odd and even respectively. Note that the first element of each row is considered as odd positioned.Examples: Input: 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9
8 min read
Count N-digit numbers such that every position is divisible by the digit at that position
Given a positive integer N, the task is to count the number of N-digit numbers such that every index (1-based indexing) in the number is divisible by the digit occurring at that index. Since the court can be very large, print it modulo 109 + 7. Examples: Input: N = 2Output: 2Explanation: The numbers 11 and 12 are the only 2-digit numbers satisfying
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg