简体   繁体   English

用C#对两个字母进行异或运算,不对称

[英]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. 这个想法是,A = 0,B = 1,C = 2,依此类推,并以关键符号对消息进行逐个符号化。 For some reason, if I xor 'B' and 'A', and 'A' and 'B' I get different results. 由于某些原因,如果我对“ B”和“ A”以及“ A”和“ B”进行异或运算,则会得到不同的结果。 Why am I getting that? 我为什么得到那个?

Addition has higher precedence than XOR. 加法的优先级高于XOR。 You're missing a pair of parentheses around the XOR operation. 您在XOR操作周围缺少一对括号。

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') . 您的代码正在计算((message[i]) - 'A') ,然后向其添加A然后(key[j] - 'A') 进行异或。 You need to wrap the XOR operation in parenthesis so that the conversion back to a char happens afterwards. 您需要将XOR操作包装在括号中,以便随后转换回char

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. 但是,如果您将整个操作分解成几个不同的语句,而不是试图在同一行上做很多不同的事情,那么整个操作将更加清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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