Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java XOR with three true inputs returns true. Why?

Tags:

java

logic

xor

The following code

System.out.println("1 0 0: " + (true ^ false ^ false));
System.out.println("1 0 1: " + (true ^ false ^ true));
System.out.println("1 1 0: " + (true ^ true ^ false));
System.out.println("1 1 1: " + (true ^ true ^ true));
System.out.println("0 0 0: " + (false ^ false ^ false));
System.out.println("0 0 1: " + (false ^ false ^ true));
System.out.println("0 1 0: " + (false ^ true ^ false));
System.out.println("0 1 1: " + (false ^ true ^ true));

outputs:

1 0 0: true
1 0 1: false
1 1 0: false
1 1 1: true
0 0 0: false
0 0 1: true
0 1 0: true
0 1 1: false

Why does XOR returns true when all three inputs are true?

If it's valid logic how can I implement logic that returns true only if one of the input elements is true (no matter how many inputs I provide)?

like image 555
parxier Avatar asked Jun 03 '11 01:06

parxier


People also ask

How does a 3 input XOR gate work?

For 3 or more inputs, the XOR gate has a value of 1when there is an odd number of 1's in the inputs, otherwise, it is a 0. Notice also that the truth tables for the 3-input XOR and XNOR gates are identical.

How does XOR operator work in Java?

The XOR logical operation, exclusive or, takes two boolean operands and returns true if, and only if, the operands are different. Conversely, it returns false if the two operands have the same value.

Does Java have XOR?

Bitwise XOR (exclusive or) "^" is an operator in Java that provides the answer '1' if both of the bits in its operands are different, if both of the bits are same then the XOR operator gives the result '0'. XOR is a binary operator that is evaluated from left to right.

Which of the following logical operator is used for XOR operation?

Exclusive or (XOR, EOR or EXOR) is a logical operator which results true when either of the operands are true (one is true and the other one is false) but both are not true and both are not false.


1 Answers

If you want a true result, if one and only one inputs is true you can use:

(a ^ b ^ c ) ^ ( a && b && c )

the test case result:

true true true = false
true true false = false
true false true = false
true false false = true
false true true = false
false true false = true
false false true = true
false false false = false
like image 89
Gonçalo Avatar answered Oct 05 '22 23:10

Gonçalo