问题
public class Operators {
public static void main(String[] args) {
int a = 12;
System.out.println("Bitwise AND:"+(12&12));
System.out.println("Bitwise inclusive OR:"+(12|12));
System.out.println("Bitwise exclusive OR:"+(12^12));
}
}
OUTPUT:
Bitwise AND:12
Bitwise inclusive OR:12
Bitwise exclusive OR:0
I understand first two, but not the third.
回答1:
XOR tells whether each bit is different.
1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 0 = 0
In other words "either but not both"
0011 XOR 0101 = 0110
回答2:
BITWISE INCLUSIVE OR (|) means normal or operation ,
BITWISEE ExCLUSIVE OR (^) means xor operation
回答3:
Third one is an XOR operation (Xclusive-OR)
It says, OR should be exclusively: where similar will be False(0) and dissimilar will be True(1).
So 12 in binary would be 1100
So, perform bitwise XOR here:
1 1 0 0
1 1 0 0
---------
0 0 0 0
---------
Every column has same digit, either both are 1's or both are 0's XOR says, both should be different. Hence all zeros
回答4:
Exclusive or (XOR
) is defined as:
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0
That is, it is 0
when two values are the same, 1
if they are different.
So, given two bit patterns which are exactly equal, each XORed bit will evaluate to 0
, as each bit will either have 1
in both positions, or 0
in both positions.
回答5:
as the operators you used are bitwise operators, so the operands are converted to bits and then operator acts on them.
here 12 -> 1100 in binary digits (bits)
and the operations of &(AND), |(OR) and ^(Exclusive OR or XOR) operators are as follows:
A B & | ^
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
so when you are performing 12^12:
A=1100
B=1100
A B ^
1 1 0
1 1 0
0 0 0
0 0 0
and 0000 -> 0 in decimal system
hence you are getting 12^12=0 in your third answer
来源:https://stackoverflow.com/questions/16642788/difference-between-bitwise-inclusive-or-and-exclusive-or-in-java