Java USES xor to implement variable swaps and xor encryption and decryption examples

  • 2020-04-01 02:53:37
  • OfStack


import java.util.Scanner;
public class VariableExchange {
    public static void main(String[] args){
        System.out.println(" Please enter variables A The value of the ");
        Scanner scanner=new Scanner(System.in);
        long A=scanner.nextLong();
        System.out.println(" Please enter variables B The value of the ");
        Scanner scannerB=new Scanner(System.in);
        long B=scannerB.nextLong();
        System.out.println("A="+A+"t"+"B="+B);
        System.out.println(" Perform variable swap ...");
        A=A^B;
        B=B^A;
        A=A^B;
        System.out.println("A="+A+"t"+"B="+B);
    }
}

The implementation is a clever use of xor operations.

The principle:


a = a ^ b;
b = b ^ a;
a = a ^ b;

namely


a1=a^b
b=a1^b=(a^b)^b=a
a=a1^b =a1^(a1^b)=a1^a1^b=b

The same variable is equal to itself with another variable and its or value.

The same principle applies to encryption. If the value and key are xor the encrypted string is obtained, the decryption operation only needs to be xor with key again.

Supplement:
Scanner class:
A simple text scanner that USES regular expressions to parse basic types and strings.
Case 1:


Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Example 2:


Scanner sc = new Scanner(new File("myNumbers"));
 while (sc.hasNextLong()) {
       long aLong = sc.nextLong();
}


Related articles: