Java中多个操作数的按位异或

时间:2017-04-22 23:51:07

标签: java bit-manipulation xor bitwise-xor

我想对多个操作数进行按位操作,这样当只有一个整数在这个位置有1位时,输出的整数为1,否则为0。

我正在使用: (a ^ b ^ c ^ d ^ e ^ f ^ g ^ h ^ i)^(a& b& c& d& e& f& g& h& i)

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

我想得到:

   0111001110

然而,我正在获得:

   0111101110

知道为什么吗?或者我应该修改什么?

2 个答案:

答案 0 :(得分:5)

实际上你可以通过按位运算来计算。

int atLeastOne = 0将是一个掩码,表示在1个或多个输入中设置的位。

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;

答案 1 :(得分: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