Java 运算符

按位异或和赋值运算符 (^=) 为第一个操作数分配一个等于两个操作数按位异或运算结果的值。

(x ^= y) 为等价于 (x = x ^ y)

按位异或运算符 (^) 是一个二元运算符,它采用两个长度相等的位模式,并对每对对应位执行逻辑异或运算。如果只有一位为 1,则返回 1,否则返回 0。

Bit_1

th>
Bit_2Bit_1 ^ Bit_2
000
101
0 11
110

下面的示例描述了按位异或运算符的工作原理:

50 ^ 25 returns 43

     50    ->    110010  (In Binary)
   ^ 25    ->  ^ 011001  (In Binary)
    ----        --------
     43    <-    101011  (In Binary)  

使用按位异或和赋值运算符(^=)的代码如下:

public class MyClass {
  public static void main(String[] args) {
    int x = 50;
    int y = 25;

    //按位异或和赋值运算
    x ^= y;

    //显示结果
    System.out.println("x = "+ x);
  }
}

输出上述代码的内容为:

x = 43

示例:在不使用临时变量的情况下交换两个数字

按位异或和赋值运算符可用于交换两个值变量。考虑下面的示例。

public class MyClass {
  static void swap(int x, int y) {
    System.out.println("Before Swap.");
    System.out.println("x = " + x);
    System.out.println("y = " + y);

    //交换技术
    x ^= y;
    y ^= x;
    x ^= y;

    System.out.println("After Swap.");
    System.out.println("x = " + x);
    System.out.println("y = " + y);
  }

  public static void main(String[] args) {
    swap(10, 25);
  }
}

上面的代码将给出以下输出:

Before Swap.
x = 10
y = 25
After Swap.
x = 25
y = 10