C++ 确定字符中的设置位数

C++ 确定字符中的设置位数,c++,c,C++,C,如果每个单位存储为一个设定位,则该程序应确定变量c_val的值中存储了多少个单位。 我的问题是:作者为什么要编写if(c%2==1)count++然后使用此语句将c向右移动c=c>>1 #include <stdio.h> #include <cstdlib> int main(){ unsigned char c_val; printf("char value = "); scanf("%c", &c_val); int cou

如果每个单位存储为一个设定位,则该程序应确定变量
c_val
的值中存储了多少个单位。 我的问题是:作者为什么要编写
if(c%2==1)count++
然后使用此语句将
c
向右移动
c=c>>1

#include <stdio.h>
#include <cstdlib>

int main(){
    unsigned char c_val;
    printf("char value = ");
    scanf("%c", &c_val);
    int count = 0;
    unsigned char c = c_val;
    while(c){
        if (c % 2 == 1) count++;
        c = c >> 1;
    }
    printf("%d bits are set", count);
    system("pause");
}
#包括
#包括
int main(){
无符号字符c_val;
printf(“char value=”);
scanf(“%c”、&c_val);
整数计数=0;
无符号字符c=c_val;
而(c){
如果(c%2==1)计数++;
c=c>>1;
}
printf(“设置了%d位”,计数);
系统(“暂停”);
}

类型char的数据大小始终为一个字节-无例外。但是,此代码计算
c_val
中的1位数

我们可以从中翻译相关代码

while (c) {
    if (c % 2 == 1) count++;
    c = c >> 1;
}

我所做的最后一个更改之所以有效,是因为将无符号整型数据类型(在本例中为
unsigned char
)右移相当于除以2,语义是四舍五入到零


我们可以把
c
想象成一条比特传送带——零比特从左边进入,而在每次循环迭代中,一比特从右边掉下来。如果最右边的位是1,我们将计数增加1,否则计数保持不变。因此,一旦
c
被零位填充,我们就知道我们已经计算了所有的一位,并且准确地说是一位,因此
count
包含
c\u val

中的一位数,这根本不是确定
char
类型实例的“大小”的函数,而是确定字符中设置为1的位数

表情

c % 2 == 1
确定最低有效位是否为1

移位将第二个至最后一个位移到最后一个位置,以便对其进行测试


while(c)
的条件意味着持续计数1s并移位,直到整个字节都为零。

您的代码只是编码字符c中有多少个1位。“c%2==1”检查“c”中的最后一位是否为1。因此,我们必须使用“c=c>>1”将“c”中的其他位移到最后一个位置

其他方法也可以这样做:

#包括
#包括
无符号整数f(无符号整数a,无符号整数b);
无符号整数f(无符号整数a,无符号整数b)
{

返回a?f((a&b)一个小的可读性改进,依我看,如果(c&0x1)count++
,将是
。我觉得它更清楚地表明您正在显式测试位。另外,它可以更快地引导。:-@AdamMihalcin:为什么不使用>>而不是2除法?
c % 2 == 1
#include <stdio.h>
#include <conio.h>

unsigned int f (unsigned int a , unsigned int b);

unsigned int f (unsigned int a , unsigned int b)
{
   return a ?   f ( (a&b) << 1, a ^b) : b;
}

int bitcount(int n) {
    int tot = 0;

    int i;
    for (i = 1; i <= n; i = i<<1)
        if (n & i)
            ++tot;

    return tot;
}

int bitcount_sparse_ones(int n) {
    int tot = 0;

    while (n) {
        ++tot;
        n &= n - 1;
    }

    return tot;
}

int main()
{

int a = 12;
int b = 18;

int c = f(a,b);
printf("Sum = %d\n", c);

int  CountA = bitcount(a);
int  CountB = bitcount(b);

int CntA = bitcount_sparse_ones(a);
int CntB = bitcount_sparse_ones(b);

printf("CountA = %d and CountB = %d\n", CountA, CountB);
printf("CntA = %d and CntB = %d\n", CntA, CntB);
getch();

return 0;

}