假设有一个整数为x,编写两个函数将x的二进制位的第n位置1或清零,其他位不变
如有x=10,二进制表示为:00000000 00000000 00000000 00001010,二进制位的最右边称为第一位,比如将第二位的1清为0,则为:00000000 00000000 00000000 00001000 = 8,
将第三位置为1,则为: 00000000 00000000 00000000 00001110 = 14。
代码实现为:
-
#include <iostream>
-
using namespace std;
-
-
#define IBS(n) 0x01<<(n-1)
-
-
void Set_N_To_1(int &x, int n)
-
{
-
x |= IBS(n);
-
}
-
-
void Clear_N_To_0(int &x, int n)
-
{
-
x &= ~IBS(n);
-
}
-
-
int main()
-
{
-
int x = 10;
-
Set_N_To_1(x, 3);
-
cout<<x<<endl;
-
x = 10;
-
Clear_N_To_0(x, 2);
-
cout<<x<<endl;
-
-
return 0;
- }
-
http://blog.chinaunix.net/uid-25132162-id-1641515.html