付费节点推荐
免费节点
节点使用教程
一、基本位操作
| |
或 |
& |
与 |
~ |
取反 |
^ |
异或 |
<< |
左移 |
>> |
右移 |
二、位操作的常见用法
1.获取某位的值
[cc lang="c"]
#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位取反
[/cc]
2.设定某位的值(设为0或1)
方法一:
[cc lang="c"]
#define setbit(x,y) x|=(1<
[cc lang="c"]
置0,用0去‘与’
int a|=(1<
[cc lang="c"]
#define ROTATE_LEFT(x, n) ((x) << (n)) | ((x) >> ((8 * sizeof(x)) - (n)))
#define ROTATE_RIGHT(x, n) ((x) >> (n)) | ((x) << ((8 * sizeof(x)) – (n)))
[/cc]
4.计算绝对值
[cc lang="c"]
int abs(int x){
int y;
y = x>>31;
return (x^y)-y; //or:(x+y)^y
}
[/cc]
5.判断整数的符号
[cc lang="c"]
int sign(int x){
return (x>>31)|(unsigned(-x))>>31;
}
[/cc]
6.两个数比较
[cc lang="c"]
x==y: ~(x-y|y-x)
x!=y: x-y|y-x
x
[cc lang="c"]
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 ;
[/cc]
8.位计数
方法一:
[cc lang="c"]
int count(long v){
int number = 0;
while(v){
v &= (v-1);
number++;
}
return number;
}
[/cc]
方法二:
[cc lang="c"]
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;
}
[/cc]
9.二进制和GRAY码的转换
(1).二进制码到GRAY码的转换:
[cc lang="c"]
unsigned B2G(unsigned B ){
return B ^ (B>>1) ;
}
[/cc]
(2).GRAY码到二进制码:
[cc lang="c"]
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 ;
}
[/cc]
10.位反转
[cc lang="c"]
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) ;
return x ;
}
[/cc]
转载自胡超博客:http://imhuchao.com/423.html
评论前必须登录!
登陆 注册