Set bits in M equals to N in the given range

By | December 14, 2022

Two numbers: m and n are given. The size of these numbers is 32-bit long. You are also given two-bit positions: i and j. You have to set all bits between i and j in m equal to n, i.e., means that n becomes a substring of m located at i and starting at j.

Examples:

Input : m = 32, n = 7, i = 1, j = 3   
Output : 46
Explanation : m (in binary) = 100000
              n (in binary) = 000111
              Set 1st bit to 3rd bit (both inclusive) of m equal to n
              output (in binary) = 101110
Input : m = 1024, n = 21, i = 2, j = 6
Output : 1108

Approach:

  1. Create a mask of 1’s with 0’s between i and j (both inclusive).
  2. ANDing the mask with m.
  3. ORing with left-shifted (by i bits) n gives the output result.

Implementation in C++ :

#include <bits/stdc++.h>
using namespace std;

//function to set all bits between i and j in m equal to n
int bit_mask (int m, int n, int i, int j)
{
    //All 1's
    int max = ~0;
    
    //1's through position j, then 0's
    int left = max - ((1 << j) - 1);

    //1's after position i
    int right = (1 << i) - 1;

    //1's, with 0's between i and j
    int mask = left | right;

    //Clear i through j, then put n in there
    return (m & mask) | (n << i);
}

//Driver program
int main() 
{
    int m = 1024, n = 21, i = 2, j = 6;
    cout << bit_mask (m, n, i, j);
    return 0;
}

Output:

1108

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.