Reputation: 35502
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?
Upvotes: 8
Views: 26547
Reputation: 93565
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.
Upvotes: 22
Reputation: 339786
If the purpose of the &
operation is to check whether bit 1 is set, then a potential "opposite" operation is 'set bit 1'.
i.e.:
val = val | 2;
This overwrites the value currently in bit 2, and doesn't touch any other bit.
If the 8 bits in the byte are considered to be completely independent bits then it's possible to change any of them with touching any of the others.
In this case, it doesn't matter that some of the original information was lost. We don't actually care what value the other bits had, and most often when using bit masks the original value of the bit in question was zero anyway.
Upvotes: 0
Reputation: 429
What do you mean by opposite calculation?
If you see the number 254 as an bit register consisting of 8 bits then all bits but the last is set to 1.
Calculating 254 & 2 is the same as checking whether bit number 2 in the register is set.
What is the opposite of this? Checking if all other bits are set?
Upvotes: 0
Reputation: 4012
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
Upvotes: 1
Reputation: 38346
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.
Upvotes: 32
Reputation: 1562
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).
Upvotes: 3