Search code examples
c#bitwise-operators

What is the inverse of bitwise AND in C#?


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?


Solution

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