2017-04-22 60 views
2

我想在多個操作數上按位運算,以便當只有一個整數在此位置有1位時輸出整數爲1,否則爲0。在Java中的多個操作數上按位異或運算

我使用: (一個^ B^C^d^E^F^G^H ^ⅰ)^(一個& b &Ç& d &Ë&˚F&克&ħ&ⅰ)

a: 0000001000 
b: 0000000010 
c: 1010000000 
d: 0000110000 
e: 0001000000 
f: 0000110000 
g: 1000100000 
h: 0000000100 
i: 0100000000 

我想:

0111001110 

不過,我獲得:

0111101110 

任何想法,爲什麼?或者我應該修改什麼?

+0

你會需要一個循環做到這一點,因爲每個比較而言依賴於結果以前的比較。 – Tibrogargan

回答

5

其實你可以計算,按位運算。

int atLeastOne = 0將是一個掩碼,指示在一個或多個輸入中設置的位。

int moreThanOne = 0將是一個掩碼,指示在2個或更多輸入中設置的位。

輸入x可以「添加」到那個狀態:​​

// if a bit has been set already and it is set again now, it has been set more than once 
moreThanOne |= atLeastOne & x; 
// if a bit is set now, it is set at least once 
atLeastOne |= x; 

只要做到這一切(與簡化在開始):

atLeastOne = a; 
moreThanOne |= atLeastOne & b; 
atLeastOne |= b; 
moreThanOne |= atLeastOne & c; 
atLeastOne |= c; 
moreThanOne |= atLeastOne & d; 
atLeastOne |= d; 
moreThanOne |= atLeastOne & e; 
atLeastOne |= e; 
moreThanOne |= atLeastOne & f; 
atLeastOne |= f; 
moreThanOne |= atLeastOne & g; 
atLeastOne |= g; 
moreThanOne |= atLeastOne & h; 
atLeastOne |= h; 
moreThanOne |= atLeastOne & i; 
atLeastOne |= i; 

的位已經設置正好一次如果已經設置了至少一次不超過一次:

int exactlyOne = atLeastOne & ~moreThanOne; 
+0

This Works!非常感謝你 – jkbestami

0

這裏的另一種方式做到這一點:

int a = 8; 
int b = 2; 
int c = 640; 
int d = 48; 
int e = 64; 
int f = 48; 
int g = 544; 
int h = 4; 
int i = 256; 
int result = 0; 
int [] arr = {a,b,c,d,e,f,g,h,i}; 

// go through all positions 
for (int j = 0; j < 32; j++) 
{ 
    int ones = 0; 
    // go through each number for this position 
    for (int k = 0; k < arr.length; k++) 
    { 
     int val = arr[k] & (1 << j); 
     ones += (val > 0) ? 1 : 0; 
    } 
    result += (ones == 1) ? (1 << j) : 0; 
} 
System.out.println(result); 
System.out.println(Integer.toBinaryString(result)); 

輸出

462 
111001110