How do I perform the inverse of the bitwise OR ( |=
) operator in C#? Is there a NOR bitwise operator in C# that I can use?
Scenario:
I am inheriting a base class from the .NET framework. This class has an operation which is setting a flag.
Example: flags |= 0x200;
In my derived class, I want to omit this flag setting, as if the operation flags |= 0x200;
had never happened.
Is there a way to achieve this?
The only reversible bitwise operation you have is XOR, so (a^b)^b==a .
|= is shorthand for doing an OR operation and assignment. For example,, x |= 3 is equivalent to x = x | 3 . You can also use other operators ( +, -, *, & , etc) in this manner as well. – yano.
If you want to flip bit #N, counting from 0 on the right towards 7 on the left (for a byte), you can use this expression: bit ^= (1 << N); This won't disturb any other bits, but if the value is only ever going to be 0 or 1 in decimal value (ie.
It performs bitwise OR operation on the corresponding bits of two operands. If either of the bits is 1 , the result is 1 . Otherwise the result is 0 . If the operands are of type bool , the bitwise OR operation is equivalent to logical OR operation between them.
You can AND (&
) with the inverse (~
) of the value you want to remove:
flags &= ~0x200;
If you intention is to ensure that this flag is not set. If you want to undo a previous change to this flag, then as @Russell says, XOR may be what you're after.
You can XOR the flag to remove it
flags ^= 0x200
This same operation will also turn that flag ON if it's off. XORing with masks behaves as a toggle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With