整形数据任意位置0/1:SetBit(data,n,val);
data:整形数据;
n:整形数据第n位 置0/1;
val: 取值0/1;
整形数据任意位取反:RevBit(data,n);
data:整形数据;
n:整形数据第n位 取反;
#define SetBit(data,n,val) (((val)==1)?((data)|(1<<(n))):((data)&~(1<<(n))))
#define RevBit(data,n) ((data)^(1<<(n)))
测试代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
#pragma warning(disable:4996)
#define SetBit(data,n,val) (((val)==1)?((data)|(1<<(n))):((data)&~(1<<(n))))
#define RevBit(data,n) ((data)^(1<<(n)))
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"RevBit(7,0) = "<<RevBit(7,0)<<endl;
cout<<"RevBit(7,1) = "<<RevBit(7,1)<<endl;
cout<<"RevBit(7,2) = "<<RevBit(7,2)<<endl;
cout<<"RevBit(6,0) = "<<RevBit(6,0)<<endl;
cout<<"RevBit(5,1) = "<<RevBit(5,1)<<endl;
cout<<"RevBit(3,2) = "<<RevBit(3,2)<<endl;
cout<<endl;
cout<<"SetBit(0,0,1) = "<<SetBit(0+1,0+0,1+0)<<endl;
cout<<"SetBit(0,1,1) = "<<SetBit(0+1,1+0,1+0)<<endl;
cout<<"SetBit(0,2,1) = "<<SetBit(0+1,1+1,1+0)<<endl;
cout<<"SetBit(6,0,1) = "<<SetBit(6,0,1)<<endl;
cout<<"SetBit(5,1,1) = "<<SetBit(5,1,1)<<endl;
cout<<"SetBit(3,2,1) = "<<SetBit(3,2,1)<<endl;
cout<<endl;
cout<<"SetBit(7,0,0) = "<<SetBit(7,0,0)<<endl;
cout<<"SetBit(7,1,0) = "<<SetBit(7,1,0)<<endl;
cout<<"SetBit(7,2,0) = "<<SetBit(7,2,0)<<endl;
cout<<"SetBit(6,0,0) = "<<SetBit(6,0,0)<<endl;
cout<<"SetBit(5,1,0) = "<<SetBit(5,1,0)<<endl;
cout<<"SetBit(3,2,0) = "<<SetBit(3,2,0)<<endl;
getchar();
return 0;
}
测试结果: