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 tasa de identidad
举例:
0000 0101 1010
^ 0000 0000 0000
---------------------
0000 0101 1010
② ^-1 invierte cada bit del binario (es decir, inversión 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
③ Según ① + ②
Voltear bits especificados →10101110 ^ 00001111 = 10100001
举例:
0000 0101 1010
| 0000 0000 1111
---------------------
0000 0101 0101
④ Intercambiar dos 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^6→3
y = x ^ y; → 3^6→5
x = x ^ y; → 5^3→6
⑤ Determine cuántos bits deben cambiarse en el binario del entero m para convertirse en n
Este escenario consiste en encontrar los diferentes bits de dos números binarios y cambiar la diferencia para que sea igual, por lo que basta con contar los diferentes lugares, de hecho, es calcular el número de unos en el binario del XOR
. de m y 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