我想编写一个程序来比较两个数字得到1位数。我想比较任意两个数字之间的比特,以找出二进制数在1和0和0中的不同之处。换句话说,"独家OR" (异)关系。
喜欢22(具有10110
二进制)并将其与15(具有01111
二进制)进行比较
第一个是10110
。
第二个是01111
。
结果:11001
。
答案是25,但我想要的是3,其中有三个1
和0
s不同。
答案 0 :(得分:4)
要查找不同的位,您需要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
要计算result
中的1位,您可以使用:
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);
在一步中执行此操作:
unsigned int count = CountBits(first ^ second);
在某些系统上,可以使用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;
}
打印:
result: 25 - count: 3
或者,具有额外功能:
#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;
}
答案 1 :(得分:0)
int count_bit(unsigned int x, unsigned int y){
int x1[31], y1[31];
unsigned int x_count = sizeof(x) * 8 - 1; /*x is of "unsigned int" type*/
unsigned int y_count = sizeof(y) * 8 -1;
for (int i = 0; i<=x_count; i++){
x1[i] = x << i;}
for (int j = 0; j<= y_count;j++){
y1[j] = y << j;}
while( (i<= x_count) && (j<= y_count)){
if( x1[i] != y1[j]){
count++;
i++;
j++;
return count;}
else
return 0;
}