Java 运算符

按位异或运算符 (^) 是一个二元运算符,它采用两个长度相等的位模式,并对每对对应位执行逻辑异或运算。如果只有一位为 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;
    int z;

    //按位异或运算
    z = x ^ y;

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

上面的输出代码为:

z = 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 = x ^ y;
    y = x ^ y;
    x = y ^ x;

    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