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

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.