What's the difference between XOR and NOT-EQUAL-TO?

前端 未结 6 2079
北恋
北恋 2020-12-15 17:11

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

相关标签:
6条回答
  • 2020-12-15 17:20

    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.

    0 讨论(0)
  • 2020-12-15 17:23

    They should be essentially the same in this case.

    0 讨论(0)
  • 2020-12-15 17:25

    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.

    0 讨论(0)
  • 2020-12-15 17:26

    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)

    0 讨论(0)
  • 2020-12-15 17:30

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

    regards, //t

    0 讨论(0)
  • 2020-12-15 17:37

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

    0 讨论(0)
提交回复
热议问题