c# - Removing enum flags -
i'm little bit puzzled removal of enum flags honest.
let me create example, let's have enum looks this
[flags] enum letter { = 1, // 1 b = 2, // 10 c = 4 // 100 }
now if want create variable hold flags letter.ab
foo = letter.a | letter.b
. makes sense me, can calculate , create sense:
01 or 10 = 11 = 3 = 1 + 2 = + b = ab
when comes removing flags, puzzled however, intuitively utilize xor operator so, this:
bar = letter.a | letter.b | letter.c // set bar abc // let's remove letter.c bar = bar ^ (letter.a | letter.b)
calculating hand should yield:
111 xor 011 = 100 = 4 = c = abc - (a + b) = 7 - (1 + 2)
but isn't people seem when removing enum flags, utilize and operator makes absolutely no sense me. there drawback using xor operator removing enum flags? there must i'm not seeing here, detailed clarification appreciated greatly! :)
yes, problem xor operator unless know you've got rest of flags, flip them. xor operation isn't "remove c" - it's "toggle values of , b". (so if input "a,c" you'd end "b,c", example.)
&
used because it's masking. basic thought value contains bits want, , bitwise , of value input value masks it.
to remove 1 specific flag (rather retaining specific flag), you'd typically utilize ~
operator create mask of "all flag". example:
var mask = ~letter.a; var newvalue = originalvalue & mask; // previous values other
c# enums bit-manipulation
No comments:
Post a Comment