Java位运算 异或运算的用途

1. 归零律:a^a=0
2. 恒等律:a^0=a, 0^a=a
3. 交换律:a^b = b^a
4. 结合律:a^b^c = (a^b)^c = a^(b^c)
5. 自反律:a^b^a = b
6. 	      a^b^c^d=0
	      a=b^c^d
	      b=c^d^a
	      c=d^a^b
	      d=a^b^c

① ^0恒等率

举例:
   0000 0101 1010
^  0000 0000 0000
---------------------
   0000 0101 1010

② ^-1翻转二进制每一位 (即按位取反)

# a ^ -1 = 翻转二进制每一位

举例:
   0000 0101 1010
|  1111 1111 1111
---------------------
   1111 1010 0101

   1000 0101 1010
|  1111 1111 1111
---------------------
   0111 1010 0101
System.out.println("素材 -1   : " + proFillZero(Integer.toBinaryString(-1)));

System.out.println("素材 13   : " + proFillZero(Integer.toBinaryString(13)));
System.out.println("素材 ~13  : " + proFillZero(Integer.toBinaryString(~13)));
System.out.println("素材 13^-1: " + proFillZero(Integer.toBinaryString(13 ^ -1)));

System.out.println("素材-13   : " + proFillZero(Integer.toBinaryString(-13)));
System.out.println("素材~-13  : " + proFillZero(Integer.toBinaryString(~-13)));
System.out.println("素材-13^-1: " + proFillZero(Integer.toBinaryString(-13 ^ -1)));

素材 -1   : 11111111111111111111111111111111

素材 13   : 00000000000000000000000000001101
素材 ~13  : 11111111111111111111111111110010
素材 13^-1: 11111111111111111111111111110010

素材-13   : 11111111111111111111111111110011
素材~-13  : 00000000000000000000000000001100
素材-13^-1: 00000000000000000000000000001100

③ 根据 ① + ②

翻转指定位 → 10101110 ^ 00001111 = 10100001

举例:
   0000 0101 1010
|  0000 0000 1111
---------------------
   0000 0101 0101

④ 交换两个数

int x = 5;
int y = 6;

x = x ^ y;
y = x ^ y; 即:y = x ^ y ^ y → x
x = x ^ y; 即:x = x ^ y → x ^ y ^ y(已经是x了) → y

System.out.println(x);// 6
System.out.println(y);// 5

x = x ^ y;5^63
y = x ^ y;3^65
x = x ^ y;5^36

⑤ 判断整数 m 的二进制需要改变多少位才能变为 n

此场景就是找2个二进制数不同的位,把不同的为改一下就相同了,故统计出不同的地方即可
其实就是计算 m 与 n 的异或的二进制中 1 的个数

private static void coutDiff(int num1, int num2) {
    
    
    System.out.println(proFillZero(Integer.toBinaryString(6)));
    System.out.println(proFillZero(Integer.toBinaryString(10)));
    
    String str = proFillZero(Integer.toBinaryString(num1 ^ num2));
    System.out.println(str);
    
    long count = Arrays.stream(str.split("")).filter("1"::equals).count();
    System.out.println(count);
}

00000000000000000000000000000110
00000000000000000000000000001010
00000000000000000000000000001100
2

猜你喜欢

转载自blog.csdn.net/weixin_37646636/article/details/132675998