What's the difference between XOR and NOT-EQUA

2019-02-05 16:54发布

问题:

My question uses Java as an example, but I guess it applies to probably all.

Is there any practical difference between the XOR operator ( ^ in java) and the NOT-EQUAL-TO ( != in java), when comparing booleans?

I evaluated things here, but I just kept wondering (seems weird, two things equal)... and didn't find anything on the net. Just one discussion in some forum that ended quickly without any result.

回答1:

For Boolean values, they mean the same thing - although there's a compound assignment operator for XOR:

x ^= y;

There's no equivalent compound assignment operator for inequality.

As for why they're both available - it would be odd for XOR not to be available just because it works the same way as inequality. It should logically be there, so it is. For non-Boolean types the result is different because it's a different result type, but that doesn't mean it would make sense to remove XOR for boolean.



回答2:

As stated in the Java Language Specification:

The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.22.2) when applied to boolean operands.

In addition if you try looking at bytecode of a simple snippet:

void test(boolean b1, boolean b2) {
    boolean res1 = b1^b2;
    boolean res2 = b1!=b2;
}

you obtain:

test(ZZ)V
   L0
    LINENUMBER 45 L0
    ILOAD 1
    ILOAD 2
    IXOR
    ISTORE 3
   L1
    LINENUMBER 46 L1
    ILOAD 1
    ILOAD 2
    IXOR
    ISTORE 4
   L2
    LINENUMBER 47 L2
    RETURN
   L3

This assures that, in addition to the same semantics, there's no any actual practical difference in implementation. (you can also see that internally ints are used to store boolean values)



回答3:

Yes, you can use XOR to test booleans for (in)equality, although the code is less intuitive: if (x ^ y) versus if (x != y).



回答4:

With boolean values, there should be no difference. You should choose whichever is more appropriate for your sense of operation.

Example:

bool oldChoice = ...;
bool newChoice = ...;
if (oldChoice != newChoice)
    ...

Here XOR would give the same result, but will not reflect the real code intention.



回答5:

They should be essentially the same in this case.



回答6:

There's a big difference, XOR works at bit-level, keeping differences as ones, so 0b0011 xor 0b1101 => 0b1110

regards, //t