I have two strings
String s1="426F62";
String s2="457665";
The strings are in hex representation. I want to XOR them. XORing normally character by character gives the correct result for others except F XOR 6
.(It gives 112, the answer should be 9)
Please tell me the correct way to implement it in JAVA
EDIT: Converting to int and xoring works. But how to xor when two strings are of different length.
The caret symbol(^) is used as the XOR operator in Java and it can work on all primitive data types. We also implemented a method to find the XOR of two binary strings.
Approach: The idea is to iterate over both the string character by character and if the character mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string.
The XOR function returns a string that is the logical XOR of the argument strings. This function takes the first argument string, does an XOR operation with the next string, and then continues to do XOR operations for each successive argument using the previous result.
The XOR is commutative so it starts with the first two hexadecimal numbers, XORs them together, and gets the result. Then it XORs the result with the third hexadecimal and gets the next result.
Rather than XORing the Unicode representations, just convert each character into the number it represents in hex, XOR those, then convert it back to hex. You can still do that one character at a time:
public String xorHex(String a, String b) {
// TODO: Validation
char[] chars = new char[a.length()];
for (int i = 0; i < chars.length; i++) {
chars[i] = toHex(fromHex(a.charAt(i)) ^ fromHex(b.charAt(i)));
}
return new String(chars);
}
private static int fromHex(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
throw new IllegalArgumentException();
}
private char toHex(int nybble) {
if (nybble < 0 || nybble > 15) {
throw new IllegalArgumentException();
}
return "0123456789ABCDEF".charAt(nybble);
}
Note that this should work however long the strings are (so long as they're the same length) and never needs to worry about negative values - you'll always just get the result of XORing each pair of characters.
Try this:
String s1 = "426F62";
String s2 = "457665";
int n1 = Integer.parseInt(s1, 16);
int n2 = Integer.parseInt(s2, 16);
int n3 = n1 ^ n2;
String s3 = String.format("%06x", n3);
Why are you storing hex values as strings? it'd be a much better idea to represent hex numbers as hex integers or longs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With