1
votes

I am trying to find out if one bitmask has at least one of the same bits set as in another bitmask. I couldn't seem to find a bitwise operator that does this, so I came up with this code that works, though I can't say I really like it.

[Flags]
enum TestFlags { a = 1, b = 2, c = 4, d = 8 }

static void Main(string[] args)
{
    TestFlags
        bm1 = TestFlags.a | TestFlags.d,
        bm2 = TestFlags.b | TestFlags.c | TestFlags.d;

    var SetFlags = Enum.GetValues(typeof(TestFlags))
        .Cast<TestFlags>()
        .Where(v => bm1.HasFlag(v));

    foreach (var e in SetFlags.Where(f => bm2.HasFlag(f)))
    {
        Console.WriteLine(e.ToString());
    }
}

Is there any more elegant way to perform this check?

2

2 Answers

1
votes

Sure, just use the bitwise-AND operator (&):

var bm3 = bm1 & bm2; // TestFlags.d

This will return a new value which has a flag set for every bit that was set in both bm1 and bm2.

And if you want to see if any bits are set in this new value, you can just compare it to 0:

Console.WriteLine(bm3 != 0); // True
1
votes

Use the and operator and compare the result to zero, for example:

(bm1 & bm2) != 0

If it's true, then they have at least 1 bit in common.