Elegantly determine if more than one boolean is "true"

Posted by Ola Tuvesson on Stack Overflow See other posts from Stack Overflow or by Ola Tuvesson
Published on 2008-12-18T14:27:48Z Indexed on 2010/06/06 3:12 UTC
Read the original article Hit count: 239

Filed under:
|
|

I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as long as we're not talking about specific built-in functions).

One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like if(myByte && (myByte >> 1)) But this would require converting the separate booleans to a byte (via a bitArray?) and that seems a bit (pun intended) clumsy... [edit]Sorry, that should have been if(myByte & (myByte - 1)) [/edit]

Note: This is of course very close to the classical "population count", "sideways addition" or "Hamming weight" programming problem - but not quite the same. I don't need to know how many of the bits are set, only if it is more than one. My hope is that there is a much simpler way to accomplish this.

© Stack Overflow or respective owner

Related posts about c#

Related posts about populationcount