Copy set bits in a range in C++


In this tutorial, we will be discussing a program to copy set bits of one number to another in the given range.

For this we will be provided with two integers. Our task is to see the bits in the first number and set those bits in the second number as well if they are in the given range. Finally returning the digit produced.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//copying set bits from y to x
void copySetBits(unsigned &x, unsigned y,
unsigned l, unsigned r){
   //l and r should be between 1 and 32
   if (l < 1 || r > 32)
      return ;
   for (int i=l; i<=r; i++){
      int mask = 1 << (i-1);
      if (y & mask)
      x = x | mask;
   }
}
int main() {
   unsigned x = 10, y = 13, l = 2, r = 3;
   copySetBits(x, y, l, r);
   cout << "Modified x: " << x;
   return 0;
}

Output

Modified x: 14

Updated on: 29-Jan-2020

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements