XOR-ing strings in C#

落爺英雄遲暮 提交于 2020-01-12 07:23:48

问题


I recently started playing around with C#, and I'm trying to understand why the following code doesn't compile. On the line with the error comment, I get:

Cannot implicitly convert type 'int' to 'char'. An explicit conversion exits (are you missing a cast?)

I'm trying to do a simple XOR operation with two strings.

public string calcXor (string a, string b)
{
    char[] charAArray = a.ToCharArray();
    char[] charBArray = b.ToCharArray();
    char[] result = new char[6];
    int len = 0;

    // Set length to be the length of the shorter string
    if (a.Length > b.Length)
        len = b.Length - 1;
    else
        len = a.Length - 1;

    for (int i = 0; i < len; i++) {
        result[i] = charAArray[i] ^ charBArray[i]; // Error here
    }

    return new string (result);
}

回答1:


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]);



回答2:


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;
}



回答3:


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.



来源:https://stackoverflow.com/questions/14971836/xor-ing-strings-in-c-sharp

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