Tuesday, 12 December 2017

java - Is it possible to use XOR to detect if exactly one of multiple conditions is true?

itemprop="text">

E.g.,



if
(bool1 ^ bool2 ^ bool3 ^ bool4)
{
// Do
whatever

}


It
should execute only if exactly one of the conditions is met.



Answer




Add the bools together as integers and check
if they equal 1.



In a language where casting
from a boolean to an integer doesn't work, such as Java, the more long winded option
is:



if ((bool1 ? 1 : 0) + (bool2 ? 1 : 0) + (bool3 ? 1
: 0) + (bool4 ? 1 : 0) == 1) {

// only runs when one of bool 1-4
is
true
}


However,
in other languages where casting a boolean to an integer is valid, you can do the
following:



if ((int)(bool1) + (int)(bool2) + (int)(bool3) +
(int)(bool4) == 1) {
// only runs when one of bool 1-4 is
true
}



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...