C语言——位操作 【更多分享:http://blog.csdn.net/wqx521】
一、基本位操作
二、位操作的常见用法 1.获取某位的值 [mw_shl_code=c,true]#define BitGet(Number,pos) ((Number)|= 1<<(pos)) //把某位置1
#define BitGet(Number,pos) ((Number) &= ~(1<<(pos)) //把某位置0
#define BitGet(Number,pos) ((Number) >> (pos)&1)) //用宏得到某数的某位
#define BitGet(Number,pos) ((Number) ^= 1<<(pos)) //把Number的POS位取反[/mw_shl_code] 2.设定某位的值(设为0或1) --- 实际应用中用的比较多的 方法一: [mw_shl_code=c,true]#define setbit(x,y) x|=(1<<y) //将x的第y位置1
#define clrbit(x,y) x&=~(1<<y) //将x的第y位清0[/mw_shl_code] 方法二: 置0,用0去‘与’;置1,用1去‘或’ [mw_shl_code=c,true]int a|=(1<<i)
int a&=~(1<<i)[/mw_shl_code] 3.循环移位 [mw_shl_code=c,true]#define ROTATE_LEFT(x, n) ((x) << (n)) | ((x) >> ((8 * sizeof(x)) - (n)))
#define ROTATE_RIGHT(x, n) ((x) >> (n)) | ((x) << ((8 * sizeof(x)) - (n)))[/mw_shl_code] 4.计算绝对值 [mw_shl_code=c,true]int abs(int x)
{
int y;
y = x>>31;
return (x^y)-y; //or x+y)^y
}[/mw_shl_code] 5.判断整数的符号 [mw_shl_code=c,true]int sign(int x)
{
return (x>>31)|(unsigned(-x))>>31;
}[/mw_shl_code] 6.两个数比较 [mw_shl_code=c,true] x==y: ~(x-y|y-x)
x!=y: x-y|y-x
x
x<=y: (x|~y)&((x^y)|~(y-x))
x
x<=y: (~x|y)&((x^y)|~(y-x))//无符号x,y比较[/mw_shl_code] 7.交换两个数的值(swap) ---小心越界 [mw_shl_code=c,true]1.x^= y ; y ^= x ; x ^= y ;
2.x= x+y ; y = x-y ; x = x-y ;
3.x= x-y ; y = y+x ; x = y-x ;
4.x= y-x ; x = y-x ; x = x+y ;[/mw_shl_code] 8.位计数 方法一:[mw_shl_code=c,true]int count(long v) {
int number = 0;
while(v)
{
v &= (v-1);
number++;
}
return number;
}[/mw_shl_code]方法二:
[mw_shl_code=c,true]int count(unsigned x)
{
x = x-((x>>1)&0x55555555) ;
x = (x&0x33333333)+(x>>2)&0x33333333);
x = (x+(x>>4))&0x0f0f0f0f;
x = x+(x>>8);
x = x+(x>>16);
return x&0x0000003f;
}[/mw_shl_code] 9.二进制和GRAY码的转换 (1).二进制码到GRAY码的转换: [mw_shl_code=c,true]unsigned B2G(unsigned B )
{
return B^ (B>>1) ;
}[/mw_shl_code] (2).GRAY码到二进制码: [mw_shl_code=c,true]unsigned G2B(unsigned G)
{
unsigned B ;
B = G^ (G>>1) ;
B = G^ (G>>2) ;
B = G^ (G>>4) ;
B = G^ (G>>8) ;
B = G^ (G>>16) ;
return B ;
}[/mw_shl_code]
10.位反转 [mw_shl_code=c,true]unsigned rev(unsigned x)
{
x = (x & 0x55555555) << 1 | (x>>1) & 0x55555555;
x = (x & 0x33333333) << 2 | (x>>2) & 0x33333333;
x = (x & 0x0f0f0f0f) << 4 | (x>>4) & 0x0f0f0f0f;
x = (x<<24) | ((x&0xff00)<<8) | ((x>>8) & 0xff00) | (x>>24) ;
}[/mw_shl_code]
|