Bitwise subtraction

maxp picture maxp · Sep 23, 2011 · Viewed 7.6k times · Source

Given the enum:

[Flags]
enum foo
{
a = 1,
b = 2,
c = 4
}

then

foo example = a | b;

If I don't know if foo contains c, previously I have been writing the following

if (example & foo.c == foo.c)
    example  = example ^ foo.c;

Is there a way to do this without checking for the existance of foo.c in example?

As when it comes to additions, I can just do an OR, and if the enum value already exists in example then it doesnt matter.

Answer

Jon Skeet picture Jon Skeet · Sep 23, 2011

I think you want:

example &= ~foo.c;

In other words, perform a bitwise "AND" mask with every bit set except the one for c.

EDIT: I should add an "except" to Unconstrained Melody at some point, so you could write:

example = example.Except(foo.c);

Let me know if this would be of interest to you, and I'll see what I can do over the weekend...