Difference between bitwise inclusive or and exclusive or in java

半世苍凉 提交于 2020-01-31 05:12:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!