The use of Java bitwise XOR operation

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 identity rate

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

② ^-1 flips each bit of binary (that is, bitwise inversion)

# 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

③ According to ① + ②

Flip specified bits →10101110 ^ 00001111 = 10100001

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

④ Swap two numbers

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 how many bits need to be changed in the binary of the integer m to become n

This scenario is to find the different bits of two binary numbers, and change the difference to make it the same, so it is enough to count the different places. In fact, it is to calculate the
number of 1s in the binary of the XOR of m and 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

Guess you like

Origin blog.csdn.net/weixin_37646636/article/details/132675998