c# - C# 中的异或字符串

标签 c# xor

我最近开始研究 C#,我想了解为什么以下代码无法编译。在有错误注释的那一行,我得到:

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

我正在尝试对两个字符串进行简单的异或运算。

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

最佳答案

如果您使用 XOR-ing 来隐藏数据,请查看下面的代码。只要有必要, key 就会重复。这可能是一种更短/更好的方法:

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

关于c# - C# 中的异或字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14971836/

相关文章:

bit-manipulation - 异或可逆运算题

c++ - 暴力异或密码

c++ - 我的神经网络不起作用[XOR问题]

c# - 在 WPF MVVM 中使用 ReactiveUI 获取属性更改的先验值

c# - 在 C# .NET 中运行 SSIS 包

algorithm - CRC多项式计算

c - 异或加密的限制

c# - 在证书中设置私钥会挂起 Windows 服务

c# - 如何使 WCF 服务一次只接受一个调用

c# - 在 Web API 和 OWIN 中使用简单注入(inject)器