首先,我将列举C语言中一些常用的与位操作相关的运算符
一、移位运算符
左移操作符<<
算术左移与逻辑左移都是左边移出一位,右边补0;
右移操作符>>
逻辑右移为右边移出一位左边最高位补0,而算术右移为右边移出一位,最高位补符号位。
二、位操作符
与 &
运算法则:见0为0,全1为1;
或 |
运算法则:见1为1,全0为0;
异或^
运算法则:相同得0,相异为1;
接下来我将分享几个比较常用的对位进行操作的编程小例子
1.不使用临时变量实现数a和b的交换
#include<stdao.h>
int main(){
int a=2;
aint b=3;
a=a^b;
b=a^b;
a=a^b;
printf("a=%d,b=%d\n",a,b);
return 0;
}
2.不使用(a+b)/2这种方式,求两个数的平均值
#include <stdio.h>
int fun(int x, int y){
int ret = 0;
ret = (x & y) + ((x ^ y) >> 1);//
printf("%d\n", ret);
}
int main(){
int a, b;
printf("请输入两个数:\n");
scanf_s("%d %d", &a, &b);
fun(a, b);
return 0;
}
3.求二进制数中1的个数
//方法一
#include <stdio.h>
int main(){
int x;
int count=0;
scanf_s("%d", &x);
while (x)
{
x = x&(x - 1);
count++;
}
printf("%d\n",count);
return 0;
}
//方法二
#include <stdio.h>
int count_one_bits(int value)// 返回 1的位数
{
//1111111111111111111
int count = 0;
int i = 0;
for(i = 0;i<32;i++)
{
if(value & 1 == 1)
count++;
value = value >> 1;
}
return count;
}int main()
{
printf("%d\n",count_one_bits(-1));
return 0;
}
本文出自 “moLova” 博客,请务必保留此出处http://molova.blog.51cto.com/10594266/1684499
原文:http://molova.blog.51cto.com/10594266/1684499