C语言位操作符常用

1, 交换两个变量的值

int a = 1;
int b = 2;
a ^= b;
b ^= a;
a ^= b;

2, 求二进制中1的个数:

int a = 5;
int count = 0;
while(a){
	a = a & (a - 1); //每次把最低位丢弃, 直到a为0
	count ++;
}

3, 求二进制中0的个数

int a = 5;
int count = 0;
while(a + 1)
{
	a = a | (a + 1);
	count ++;
}

4,求一个数的绝对值

int i = -2;
int j = i >> 31;
i = (i ^ j) - j;

5, 求一个数的相反数

int i = -2;
i = ~i + 1;

6, 判断一个数的奇偶性

int a = 3;
if((a & 1) == 1){
"奇数"
}else{
"偶数"
}

7,求两个数的平均数

int a = 3;
int b = 7;
int s = (a + b) >> 1;

8,从无符号类型x的第p位开始, 取n位数

unsigned GetBits(unsigned x , int p, int n)
{
	return (x >> (p+1-n)) & ~(~0 << n);
}

你可能感兴趣的:(c语言,算法)