What does the ^ operator do in Java?

前端 未结 17 1742
执念已碎
执念已碎 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:56

    As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.

    But I think it's also useful to note that ^ is just one of a family of operators that are collectively known as bitwise operators:

    Operator    Name         Example     Result  Description
    a & b       and          3 & 5       1       1 if both bits are 1.
    a | b       or           3 | 5       7       1 if either bit is 1.
    a ^ b       xor          3 ^ 5       6       1 if both bits are different.
    ~a          not          ~3          -4      Inverts the bits.
    n << p      left shift   3 << 2      12      Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
    n >> p      right shift  5 >> 2      1       Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
    n >>> p     right shift  -4 >>> 28   15      Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.
    

    From here.

    These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.

提交回复
热议问题