简体   繁体   中英

Xor-ing two letters in C#, not symmetric

So, I have this basic encrypting function, and I'm really stuck.

String result = "";
....
result += ((char)('A' + ((message[i]) - 'A') ^ (key[j] - 'A')));

The idea is, A = 0, B = 1, C = 2, etc., and to the message with the key symbol by symbol. For some reason, if I xor 'B' and 'A', and 'A' and 'B' I get different results. Why am I getting that?

Addition has higher precedence than XOR. You're missing a pair of parentheses around the XOR operation.

result += (char)('A' + ((message[i] - 'A') ^ (key[j] - 'A')));

You need an extra set of parenthesis. Your code is computing ((message[i]) - 'A') , then adding A to that , and then XOr-ing that with (key[j] - 'A') . You need to wrap the XOR operation in parenthesis so that the conversion back to a char happens afterwards.

However this whole operation would be much clearer to read if you broke it up into several different statements, rather than trying to do so many different things all on the same line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM