XOR-ing strings in C#

橙三吉。 提交于 2019-12-03 13:03:57
allen

You are doing an xor on 2 characters. This will do an implicit type conversion to int for you since there is no data loss. However, converting back from int to char will need you to provide an explicit cast.

You need to explicitly convert your int to a char for result[i]:

result[i] = (char) (charAArray[i] ^ charBArray[i]);
Ton Snoei

If you use XOR-ing to hide data, take a look at the code below. The key will be repeated as long as necessary. It is maybe a shorter/better approach:

public static string xorIt(string key, string input)
{
    StringBuilder sb = new StringBuilder();
    for(int i=0; i < input.Length; i++)
        sb.Append((char)(input[i] ^ key[(i % key.Length)]));
    String result = sb.ToString ();

    return result;
}
mckenzm

If the value of the result is important then Allan is correct (accepted answer). If you are just looking for a match and are not worried about performance, use strcmp() or memcmp() as an alternative.

In assembler is it common to initialize things by an XOR against themselves as the T-cycles are fewer. If I was brute-forcing (hash compare), then this would be an improvement over strcmp or memcmp as I really don't sort order, just match/nomatch.

Readers should also be aware of this which can be tweaked.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!