0

Assume you have the following Enumeration, which contains flags.

[Flags]
public enum MyFlag
{
    None = 0,
    Foo = 1 << 0,
    Bar = 1 << 1,
    Baz = 1 << 2,
    Quuz = 1 << 3
}

And you instantiate a new and old :

var newF = MyFlag.Foo | MyFlaq.Quuz; // 1001
var oldF = MyFlag.Foo | MyFlag.Baz;  // 0101

My first question: How to perform a bitwise operation on new and old, getting the XOR flag ?

var xor = ?????  // -> should be    1100

Then an additional question: How to use that XOR flags, to calculate added and removed flags?

MyFlag added = ????? // Do something with new and xor -> should result in : 1000
MyFlag removed = ????? // Do same thing with old and xor -> should result in: 0100

Doing this manually on a piece of paper is super easy.

Bitwise operation on paper.

There should be some kind of bitwise operation available for this right? Please show me the answer and I will add it to my skillset! :-)

The answers are:

var xor = newF ^ oldF;
var added = newF & xor;
var removed = oldF & xor;
  • Why don't you just google for "C# bitwise operators"? – Jeroen Vannevel May 29 '17 at 10:43
  • 1
    `^`: e.g. `var xor = @new ^ old;` please, notice, that since `new` is a keyword in C# it shoould be put as `@new` when used a name. – Dmitry Bychenko May 29 '17 at 10:45
  • SO is not a format to ask this kind of questions. look it up in [documentation](https://msdn.microsoft.com/en-us/library/17zwb64t.aspx) – Cee McSharpface May 29 '17 at 10:47
  • For second question (how to set/clear bit?) see [this](https://stackoverflow.com/q/93744/1997232). – Sinatr May 29 '17 at 11:22
  • @JeroenVannevel and other downvoters: Did it ever occur to you, that online documentation that can be found in google's top search results, only show abstract documentation that lack any good example results? For me and many other people it is very useful to actually see the result of how the operator works on real data. – Tony_KiloPapaMikeGolf May 29 '17 at 11:51
  • 1
    In my opinion if you can't ask useful questions like this on stackoverflow, because some nerd on steroids thinks it is too easy to find on google, I should start a similar website, where questions like these are welcome. – Tony_KiloPapaMikeGolf May 29 '17 at 12:00

1 Answers1

3

Try ^; please, notice that new is a keyword in C# and that's why should be put as @new when it's used as a name:

  var @new = MyFlag.Foo | MyFlag.Quuz; // 1001
  var old = MyFlag.Foo | MyFlag.Baz;   // 0101

  var xor = @new ^ old; // <- xor

Test

  // 1100
  Console.Write(Convert.ToString((int)xor, 2));

Finally, it seems that you are looking for bitwise & to obtain added and removed values:

  MyFlag added = xor & @new;  // 1000
  MyFlag removed = xor & old; // 0100
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215