Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 626
Ivan Prodanov Avatar asked Apr 23 '09 19:04

Ivan Prodanov


4 Answers

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.

like image 122
Samuel Avatar answered Oct 20 '22 09:10

Samuel


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

like image 39
Adam Davis Avatar answered Oct 20 '22 09:10

Adam Davis


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

like image 3
Beardo Avatar answered Oct 20 '22 09:10

Beardo


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

like image 1
Crippledsmurf Avatar answered Oct 20 '22 10:10

Crippledsmurf