IMO it would be better to split this into two pieces. One function to do the piecewise XOR and another function to convert the byte array to a hex string.
public static byte[] exclusiveOR(byte[] arr1, byte[] arr2)
{
if (arr1.Length != arr2.Length)
throw new ArgumentException("arr1 and arr2 are not the same length");
byte[] result = new byte[arr1.Length];
for (int i = 0; i < arr1.Length; ++i)
result[i] = (byte) (arr1[i] ^ arr2[i]);
return result;
}
public static string arrayToHexString(byte[] arr)
{
var sb = new StringBuilder();
for (int i = 0; i < arr.Length; ++i)
sb.Append(arr[i].ToString("x2"));
return sb.ToString();
}
Now you can just say:
Console.WriteLine(arrayToHexString(exclusiveOR(arr1, arr2)));
The reason your solution printed bizarre characters is that you are XORing ASCII values '1'
and '0'
since those are the characters in your string. Since '1'
is 0x31 and '0'
is 0x30, the result is 0x30 xor 0x31 = 1. You are then putting ASCII character 0x01 (which is a nonprintable control character) into your result string.