Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing the inverse of (or reversing) bitwise OR in C#

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?

like image 237
Matthew Layton Avatar asked Oct 12 '12 10:10

Matthew Layton


People also ask

What is the inverse operation of Bitwise OR?

The only reversible bitwise operation you have is XOR, so (a^b)^b==a .

What is |= in C programming?

|= 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.

How do you flip a bit in C#?

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.

How does Bitwise operator work C#?

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.


2 Answers

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.

like image 196
Damien_The_Unbeliever Avatar answered Nov 07 '22 02:11

Damien_The_Unbeliever


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.

like image 45
PhonicUK Avatar answered Nov 07 '22 03:11

PhonicUK