Open In App

Extract Bits in C++

Last Updated : 08 Jul, 2024
Suggest changes
Share
Like Article
Like
Report

Extracting bits from a given number involves extracting 'k' bits starting from a specified position 'pos' by using bitwise operations like AND (&) and shifts (<<, >>). In this article, we will learn how to extract bits in C++.

Example:

Input:
num = 214
k = 3
pos = 2

Output:
5

Extracting Bits in C++

To extract k bits from a given position pos in a number, first perform right shift on num by pos bits that brings the target bits to the least significant positions, then create a mask with k bits set to 1 and apply it to shifted number (that we got after performing right shift operation) using the AND operation.

Steps to Extract Bits

Consider the above example, where num=214 (binary: 11010110), k=3 and pos=2.

  1. Right Shift: shifted = num >> pos
    • shifted = 214 >> 2 = 53 (binary: 110101)
  2. Create Mask: mask = (1 << k) - 1
    • mask = (1<<3) - 1 = 7 (binary 111)
  3. Apply Mask: result = shifted & mask
    • result = 53 & 7 = 5 (binary: 101)

C++ Program to Extract in a Number

The below program demonstrates how we can extract ‘k’ bits from a given position ‘p’ in a number.

C++
// C++ program to extract 'k' bits from position 'pos' in // number 'num' #include <iostream> using namespace std; // Function to extract 'k' bits from position 'pos' in // number 'num' unsigned int extractBits(unsigned int num, unsigned int pos,  unsigned int k) {  // Right shift 'num' by 'pos' bits  unsigned int shifted = num >> pos;  // Create a mask with 'k' bits set to 1  unsigned int mask = (1 << k) - 1;  // Apply the mask to the shifted number  return shifted & mask; } int main() {  // Example number from which bits are to be extracted  unsigned int num = 214;  // Starting position of bits to extract  unsigned int pos = 2;  // Number of bits to extract  unsigned int k = 3;  // Call the function to extract bits  unsigned int result = extractBits(num, pos, k);  // Print the result  cout << "Extracted bits: " << result << endl;  return 0; } 

Output
Extracted bits: 7 

Time Complexity: O(1), as each operation within the extractBits function (right shift, mask creation, and bitwise AND) is performed in constant time.
Auxiliary Space: O(1)


Explore