What is the reverse bitwise AND in C #?

I need to do an inverse calculation, which consists of a bitwise operation. And how to do it?

I tried an exclusive OR, but that didn't help.

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

Does not work. How to do it?

+6
c # bitwise-operators
source share
6 answers

Given i , you cannot return 254 . As a result, & you destroyed data that was not stored in the second bit.

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

How would you recover 6 lost bits? For x & 2 == 2 you can put almost any x , and that will be true.

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

Is x 254 or 42? You can not say.

+27
source share

Technically the opposite of AND - NAND:

~ (254 and 2)

Note that ~ is the complement operator and performs bitwise NOT (switches each bit to the opposite).

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

If you are trying to cancel the calculation, you cannot - there is no inverse function, so inverseand (and (x, y)) will return x or y, even if the opposite is specified by one of them.

-Adam

+21
source share

You cannot, you lost the data that was there when you did &.

4-bit example:

 1110 & 0010 = 0010 

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

+3
source share

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

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

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

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

+1
source share

What do you mean by the opposite calculation?

If you see number 254 in the form of a bit register consisting of 8 bits, then all bits except the last one are 1.

Calculation of 254 and 2 is the same as checking if bit 2 is set in the register.

What is the opposite of this? Check if all other bits are set?

0
source share

If the purpose of the & operation is to check whether bit 1 is set, then the potential β€œopposite” operation is to β€œset bit 1”.

i.e:.

 val = val | 2; 

This overwrites the value currently in bit 2 and does not apply to any other bit.

If 8 bits in a byte are considered completely independent bits, then you can change any of them by touching any other.

In this case, it does not matter that some initial information was lost. In fact, we don’t care about what value the other bits had, and most often when using bit masks, the initial value of the bits in question is zero.

0
source share

All Articles