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

Bitwise XOR on multiple operands in Java

我想对多个操作数进行按位运算,以便当只有一个整数在该位置有 1 位时输出整数为 1,否则为 0。

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


其实你可以用位运算来计算。

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

int moreThanOne = 0 将是一个掩码,指示在 2 个或更多输入中设置的位。

输入 x 可以通过以下方式"添加"到该状态:

1
2
3
4
// 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;

对所有事情都这样做(在开始时进行简化):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;

如果设置了至少一次且不超过一次,则该位已设置了一次:

1
int exactlyOne = atLeastOne & ~moreThanOne;

这是另一种方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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));

输出:

1
2
462
111001110