Utilisation de l'opération XOR au niveau du bit 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 taux d'identité

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

② ^-1 retourne chaque bit du binaire (c'est-à-dire une inversion au niveau du 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

③ Selon ① + ②

Retourner les bits spécifiés →10101110 ^ 00001111 = 10100001

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

④ Échangez deux numéros

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

⑤ Déterminer combien de bits doivent être modifiés dans le binaire de l'entier m pour devenir n

Ce scénario consiste à trouver les différents bits de deux nombres binaires, et à changer la différence pour qu'elle soit identique, il suffit donc de compter les différentes places. En fait, il s'agit de calculer le nombre de 1
dans le binaire du XOR de m et 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

Je suppose que tu aimes

Origine blog.csdn.net/weixin_37646636/article/details/132675998
conseillé
Classement