O uso da operação Java XOR bit a bit

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 taxa de identidade

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

② ^-1 inverte cada bit de binário (ou seja, inversão bit a bit)

# 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

③ De acordo com ① + ②

Inverter bits especificados →10101110 ^ 00001111 = 10100001

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

④ Troque dois números

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

⑤ Determine quantos bits precisam ser alterados no binário do inteiro m para se tornar n

Este cenário é encontrar os diferentes bits de dois números binários e alterar a diferença para torná-la igual, então basta contar as diferentes casas. Na verdade, é calcular o número
de 1s no binário do XOR de m e n.

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

Acho que você gosta

Origin blog.csdn.net/weixin_37646636/article/details/132675998
Recomendado
Clasificación