Instead of XORing Unicode representations, just convert each character to the number that it represents in hexadecimal, XOR, and then convert it back to hex. You can still do this 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 as long as the strings (if they are the same length), and you never need to worry about negative values ββ- you will always get the XORing result of each pair of characters.
Jon skeet
source share