What is the inverse of bitwise AND in C#?

20,300

Solution 1

Given i, you cannot get back 254. By &ing it you have destroyed what data was not stored in the second bit.

 1111 1110
&0000 0010
----------
 0000 0010

How would you recover the 6 lost bits? For x & 2 == 2, you could put almost any x and it would be true.

 0010 1010 // = 42
&0000 0010
----------
 0000 0010

Is x 254 or 42? You cannot tell.

Solution 2

Technically the opposite of AND is NAND:

~( 254 & 2 )

Note that the ~ is the complement operator, and does a bitwise NOT (toggle each bit to its opposite).

What exactly do you want, though? What are you trying to accomplish?

If you're trying to undo the calculation, you can't - there is no inverse function such that inverseand(and(x, y)) will return x or y, even if inverse is given one of them.

-Adam

Solution 3

You can't, you've lost the data that was there when you did the &.

4-bit example:

1110 & 0010 = 0010

You have no way of knowing which bits were 1 and which weren't if you only know the result 0010 and the second operand of the & (also 0010).

Solution 4

Wikipedia has a good article on bitwise operations, how they work and their syntax in C and Java which is very similar to C#

http://en.wikipedia.org/wiki/Bitwise_operation

MSDN of course also has documentation for each of the bitwise and logical operators each of which have an example:

http://msdn.microsoft.com/en-us/library/6a71f45d(vs.71).aspx

Share:
20,300
P. Duw
Author by

P. Duw

Updated on January 29, 2020

Comments

  • P. Duw
    P. Duw about 4 years

    I need to do an inverse calculation, which consists bitwise AND operation,how do I do it?

    I tried exclusive OR, but it didn't help.

            int i = 254 & 2;
            Console.Write("254 & 2 ={0}", i + "\n");
            Console.Write("{0} ^ 2 ={1}",i, (i ^ 2) + "\n");
    

    Doesn't work. How do I do that calculation?

  • Beska
    Beska about 15 years
    +1 partially because I think you're on the right track, but mostly because of the "what do you want" question, which is really the issue here...it's not completely obvious what he's trying to do.