ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมที่จะคัดลอกชุดบิตของตัวเลขหนึ่งไปยังอีกชุดหนึ่งในช่วงที่กำหนด
สำหรับสิ่งนี้เราจะได้รับจำนวนเต็มสองจำนวน งานของเราคือดูบิตในหมายเลขแรกและตั้งค่าบิตเหล่านั้นเป็นหมายเลขที่สองด้วยหากอยู่ในช่วงที่กำหนด ในที่สุดก็คืนหลักที่ผลิต
ตัวอย่าง
#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