Bitwise operations on Enum Flag
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.
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;
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
链接地址: http://www.djcxy.com/p/72508.html
上一篇: 在java中重复String的简单方法
下一篇: 枚举标志上的按位操作