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?
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.
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
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With