在 C++ 中複製指定範圍內的已設定位
在本教程中,我們將討論一個程式,該程式用於將一個數字的已設定位複製到另一個數字,使其在給定範圍內。
為此,我們將提供兩個整數。我們的任務是檢視第一個數字中的位,並在給定範圍內將這些位也設定在第二個數字中。最後返回產生的數字。
示例
#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; }
輸出
Modified x: 14
廣告