c - 使用按位运算符计算 1 的数量

标签 c bitwise-operators bit

我正在用 C 语言编写一个使用按位运算符的程序。这是一项学校作业,目标是计算整数的位表示形式中 1 的数量,然后如果结果是偶数,则打印“Even”,并且“奇数”如果是奇数。

我编写了一个程序来循环遍历每个位,并将输入的整数与掩码进行比较,并在每次按位 AND 运算符返回 1 时递增计数器变量。但是,该程序似乎并未递增计数器变量。代码如下:

#include <stdio.h>

void bitsEvenOrOdd(int value);

int main(void) {
    int integer;

    printf("Enter an integer: ");
    scanf("%d", &integer);

    bitsEvenOrOdd(integer);

    return 0;
}

void bitsEvenOrOdd(int value) {
    unsigned int displayMask;
    unsigned int i;
    unsigned int counter;

    counter = 0;
    displayMask = 1 << 31;

    for (i = 0; i < 32; i++) {
        if ((value & displayMask) == 1) {
            counter++;
        }
        value <<= 1;
    }

    if ((counter % 2) == 0) {
        printf("The total number of 1's in the bit representation is even.\n");
    }
    else {
        printf("The total number of 1's in the bit representation is odd.\n");
    }
}

非常感谢任何建议或提示。谢谢!

最佳答案

if ((值 & displayMask) == 1) {

考虑这个操作。 displayMask 为 0x80000000。该数字与任何其他数字之间的按位和只能是 0x80000000 或 0。您将其与 1 进行比较。

比较它是否不等于 0 或(我建议这样做),检查最低位设置并​​右移而不是左移。

关于c - 使用按位运算符计算 1 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111538/

相关文章:

algorithm - 访问 MIPS 中的各个位

c++ - 影响数字比较的双粒度c++

c - 带有信号捕捉器的套接字程序

c - 将数组和矩阵传递给函数作为 C 中的指针和指向指针的指针

c - 如何检查有符号整数是否为正数?

c++ - 一致性哈希 SHA1 模运算

c - "Marking"C 中的指针与 "attributes"

python - Python 中的 C 结构

我可以实现从基于 WCF 的 HTTP 服务到 gSOAP c/Linux 客户端的回调吗?

java - 如何在 Kotlin 中组合 Intent 标志