Elegantly determine if more than one boolean is “true”

前端 未结 22 1130
深忆病人
深忆病人 2020-12-04 13:40

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 al

22条回答
  •  孤街浪徒
    2020-12-04 14:35

    You mentioned

    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))

    I don't think that expression will give you the result you want (at least using C semantics, since the expression is not valid C#):

    If (myByte == 0x08), then the expression will return true even though there's only one bit set.

    If you meant "if (myByte & (myByte >> 1))" then if (myByte == 0x0a) the expression will return false even though there are 2 bits set.

    But here are some techniques for counting the number of bits in a word:

    Bit Twiddling Hacks - Counting bits

    A variation you might consider is to use Kernighan's counting method, but bail out early since you only need to know if there's more than one bit set:

    int moreThanOneBitSet( unsigned int v)
    {
        unsigned int c; // c accumulates the total bits set in v
    
        for (c = 0; v && (c <= 1); c++)
        {
          v &= v - 1; // clear the least significant bit set
        }
    
        return (c > 1);
    }
    

    Of course, using a lookup table's not a bad option either.

提交回复
热议问题