Finding XOR of Binary Strings
XOR only works for primitive data types. However, we can write our own method that uses the XOR operator and some additional logic to find the XOR of two binary strings.
public class XOR {
public static String binaryStringXOR(String binStr1, String binStr2) {
String xor = "";
// adding zeroes to make the two strings equal in length
if (binStr1.length() > binStr2.length()) {
String temp = "";
for (int i = 0; i < binStr1.length() - binStr2.length(); i++)
temp += "0";
binStr2 = temp + binStr2;
} else if (binStr2.length() > binStr1.length()) {
String temp = "";
for (int i = 0; i < binStr2.length() - binStr1.length(); i++)
temp += "0";
binStr1 = temp + binStr1;
}
for (int i = 0; i < binStr1.length(); i++) {
xor += binStr1.charAt(i) ^ binStr2.charAt(i);
}
return xor;
}
public static void main(String[] args) {
System.out.println("1001 XOR 1111: " + binaryStringXOR("1001", "1111"));
System.out.println("1 XOR 10100: " + binaryStringXOR("1", "10100"));
System.out.println("0111 XOR 1: " + binaryStringXOR("0111", "1"));
System.out.print("100000 XOR 0: " + binaryStringXOR("100000", "0"));
}
}
To run the code, save it to the file ~/project/XOR.java
, and execute the following commands in the terminal:
cd ~/project/
javac XOR.java
java XOR
The output will be:
1001 XOR 1111: 0110
1 XOR 10100: 10101
0111 XOR 1: 0110
100000 XOR 0: 100000