0

I have a bitwise enum variable, and I want to check if it's "single".

[Flags]
public enum Tier
{
    One   = 0b_000001,
    Two   = 0b_000010,
    Three = 0b_000100,
    Four  = 0b_001000,
    Five  = 0b_010000,
    Six   = 0b_100000,
    
    None = 0b_000000,
    All = ~None,
    
    ThreeToFive = Three | Four | Five
}


var a = Tier.One | Tier.Two // Not "single"
var b = Tier.Three          // "single"
var c = Tier.None           // Not "single"

And what I want to do is like...

var d = IsSingle(Tier.One)            // = true
var e = IsSingle(Tier.Three)          // = true
var f = IsSingle(Tier.ThreeToFive)    // = false
var g = IsSingle(Tier.One | Tier.Two) // = false
var h = IsSingle(Tier.All)            // = false

Additionally, since it is a frequently used function, the faster it operates, the better.
I've tried the following method, but I think there's a better way.

public static bool IsSingle(Tier tier)
{
    var ls = new int[6]
    {
        0b_000001,
        0b_000010,
        0b_000100,
        0b_001000,
        0b_010000,
        0b_100000
    };
    return ls.Contains((int)tier);
}

or I want to know how to check that the 6-digit binary number is the "n"th power of 2.
( = Is there only one "1" )
I think that if I solve this question, I think I can solve the above question.

000001 // "single"
000010 // "single"
010000 // "single"
010010 // Not "single"
000000 // Not "single"
  • Note that accepted answer in duplicate question only works with positive numbers, and default value for enum is `int` which is signed integer. That's very unusual to use negative numbers for enum values though, and there are none in your example. – Evk Oct 16 '21 at 15:38

0 Answers0