What does the ^ operator do in Java?

前端 未结 17 1955
执念已碎
执念已碎 2020-11-22 03:27

What function does the ^ (caret) operator serve in Java?

When I try this:

int a = 5^n;

...it gives me:

17条回答
  •  青春惊慌失措
    2020-11-22 03:46

    AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.

    The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.

    To use your example:

    • The binary representation of 5 is 0101.
    • The binary representation of 4 is 0100.

    A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

    With 4 and 5, the only difference is in the last place; so

    0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

提交回复
热议问题