2016-01-15 53 views
0

我想編寫一個程序來比較兩個數中的1位數。我想比較任意兩個數字之間的位,以找出二進制數在1和0中的不同位置。換句話說,「異或」(XOR)關係。計數兩個數中的位數並比較[C]

一樣,如果22(其具有10110二進制),並將其與15比較(其具有01111二進制)

第一個是10110。 第二個是01111

結果:11001

答案是25,但我想得到的是3有三個不同的1 s和0 s。

+1

看看[位運算符(https://en.wikipedia.org/wiki/Bitwise_operations_in_C),嘗試實現的東西,如果你將有問題的,張貼的,我們會給你一個手.. – LPs

+0

您可以選擇任何數量的位計算算法:http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32- bit-integer –

+0

還有一堆關於亂碼黑客(包括計數位)的參考:https://graphics.stanford.edu/~seander/bithacks。html –

回答

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; 
} 
+0

是的,我知道得到1位。我必須比較兩個數字看他們的位在各自的位置..假設如果兩個數字是相同的,那麼他們的位也是一樣的..要在這種情況下返回零.. –

+0

@SagunPanthi - 是的,正如你在你說的問題,你需要對它們進行異或操作:int count = CountBits(第一個^秒);''會給你異或值的位數(如果它們相同則返回0)。 ('^'是XOR運算符) –

+0

@SagunPanthi - 查看我的更新瞭解完整示例。 –

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; 
}