#include<stdio.h>
/*
* 对数字统计2进制中1的个数
* 对一个数字作与运算,将某个位置 设置为0 或者 设置为1
*/
static int count_one_bit(unsigned int a);
void main()
{
system("clear"); //清除屏幕多余信息
int a =135;
//统计一个整数有多个2进制1
printf("整数%d 含有2进制1的个数为: %d\n",a,count_one_bit(a));
//将a的第三位设置为1
printf("set pos 3 = 1 %d\n",a | 1 << 3);
//将a的第三位设置为0
printf("set pos 3 = 0 %d\n",a & ~(1<<3));
//a左移动一位,自动补充0
int b = a << 1;
printf("b is %d\n",b);
//a右移动一位,前面自动补充0
int c = a >> 1;
printf("c is %d\n",c);
}
static int count_one_bit(unsigned int a)
{
int ones;
for(ones=0; a!=0 ; a= a >>1)
{
if(a%2!=0)
ones+=1;
}
return ones;
}
c语言--移位运算,统计某个整数2进制含1的个数
最新推荐文章于 2024-02-21 15:49:59 发布