Performing a reverse (or reverse) bitwise OR in C #

How to invert the bitwise OR ( |= ) operator in C #? Is there a bitwise NOR operator in C # that I can use?

Scenario:

I inherit the base class from the .NET framework. This class has an operation that sets a flag.

Example: flags |= 0x200;

In my derived class, I want to omit this flag, as if the operation flags |= 0x200; never happened.

Is there any way to achieve this?

+6
source share
4 answers

You can AND ( & ) with the inverse ( ~ ) value you want to remove:

 flags &= ~0x200; 

If you intend to ensure that this flag is not set. If you want to undo the previous change to this flag, then, as @Russell says, XOR may be what you are after.

+8
source

You can remove the XOR flag to remove it

 flags ^= 0x200 

The same operation will also enable this flag if it is off. Masked XORing behaves like a switch.

+5
source

will not work XOR? flags ^ 0x200

+1
source

It would be difficult for you to find out if the original flag values ​​were set to these bits or not. Say flags were already 0x200 , when your code is executed, then your operation will neither change xOR, nor equal, nor guarantee that the previous value will be restored. The only way I can see is to do this operation in a virtual method and override it in the derived class without any changes. Another way would be to make this magic value a property and set it in the constructor of the derived class to 0. This will prevent the change.

0
source

Source: https://habr.com/ru/post/927552/


All Articles