
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements