计算两个数字中的位数并进行比较 [C]

Sag*_*thi 1 c

我想编写一个程序来获取比较两个数字时 1 位的数量。我想比较任意两个数字之间的位,以找出二进制数在 1 和 0 中的不同之处。换句话说,“异或”(XOR)关系。

就像如果 22(有10110二进制)并将其与 15(有01111二进制)进行比较

第一个是10110。第二个是01111

结果:11001

答案是 25,但我想要的是 3,其中三个1s 和0s 不同。

Dan*_*_ds 5

要找到不同的位,您需要找到XOR这些值:

unsigned int first  = 22;
unsigned int second = 15;
unsigned int result = first ^ second; // only the bits that are different
                                      // will be set to 1 in result
Run Code Online (Sandbox Code Playgroud)

要计算 1 位,result您可以使用:

unsigned int CountBits(unsigned int n) {

   unsigned int count = 0;
   while(n) {
       count += n & 0x01; // checks the least significant bit of n
                          // if the bit is 1, count is incremented
       n >>= 1; // shift all bits of n one to the right
                // if no 1 bits are left, n becomes 0 and the loop ends
   }
   return count;
}

unsigned int count = CountBits(result);
Run Code Online (Sandbox Code Playgroud)

要做到这一点的一个步骤

unsigned int count = CountBits(first ^ second);
Run Code Online (Sandbox Code Playgroud)

在某些系统上,POPCNT可以使用该指令代替。


更新- 完整示例:

#include <stdio.h>

unsigned int CountBits(unsigned int n) {

    unsigned int count = 0;
    while(n) {
        count += n & 0x01;
        n >>= 1;
    }
    return count;
}

int main(void) {

    unsigned int first  = 22;
    unsigned int second = 15;
    unsigned int result = first ^ second;

    unsigned int count = CountBits(result);

    printf("result: %u - count: %u\n", result, count);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

印刷:

result: 25 - count: 3
Run Code Online (Sandbox Code Playgroud)

或者,有一个额外的功能

#include <stdio.h>

unsigned int CountBits(unsigned int n) {

    unsigned int count = 0;
    while(n) {
        count += n & 0x01;
        n >>= 1;
    }
    return count;
}

unsigned int CountDifferentBits(unsigned int n1, unsigned int n2) {

    return CountBits(n1 ^ n2);
}

int main(void) {

    unsigned int count = CountDifferentBits(22, 15);

    printf("Different bits count: %u\n", count);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)