如何以二进制形式分隔字符并对它们进行校验和 C#

How to separate the character in binary form and checksum them c#

ff03c1 3d

如何异或这个字符串并得到校验和 3d ?

场景是:

我得到像 ff03c13d 这样的字符串。 (还有其他长度更长的型号)。 我应该检查十六进制的 crc;

像这样:

ff xor 03 xor c1 如果结果等于最后两个字符或最后一个字节(如 3d) return True.

感谢您的帮助

您可以使用 int.Parse with NumberStyles.HexNumber 解析值以从字符串中提取值,XOR 需要 XOR 的部分(Hex 中的每个 Hex 值15=]) 并与字符串中最后 2 个 Hex 符号表示的 CRC 进行比较。

像这样:

使用提供的字符串:

bool isValid = CRC("ff03c13d");

private bool CRC(string input)
{
    if (input.Length % 2 != 0) throw new InvalidOperationException(input);

    int result = -1;
    if (int.TryParse(input.Substring(input.Length - 2), NumberStyles.HexNumber, null, out int CRC)) {
        for (int i = 0; i < input.Length - 2; i += 2) 
        {
            if (int.TryParse(input.Substring(i, 2), NumberStyles.HexNumber, null, out int value)) { 
                result ^= value;
            } else { throw new InvalidDataException(input); }
        }
    }
    else { throw new InvalidDataException(input); }
    return result == CRC;
}

下面的函数可以对你的十六进制字符串进行异或运算

public static string GetXOR(string input)
{
    if (input.Length % 2 == 0)
    {
        int result = 0;
        for (int i = 0; i < input.Length; i = i + 2)
        {
            string hex = input.Substring(i, 2);
            int hexInt = Convert.ToInt32(hex, 16);
            result ^= hexInt;
        }

        return result.ToString("X");
    }
    return "Wrong Input";
}

你可以像这样使用它

string input = "ff03c1";
string ouput = GetXOR(input);

Console.WriteLine(ouput);
Console.ReadLine();

输出:

Linq,WhereSelectAggregateToString

var hex = "ff03c1";
var result = Enumerable.Range(0, hex.Length)
                       .Where(x => x % 2 == 0)
                       .Select(x => Convert.ToInt32(hex.Substring(x, 2), 16))
                       .Aggregate((i, i1) => i ^ i1)
                       .ToString("X");

Console.WriteLine(result);

Full Demo Here

方法

public static bool Check(string hex)
{
   return Enumerable.Range(0, hex.Length-2)
                    .Where(x => x % 2 == 0)
                    .Select(x => Convert.ToInt32(hex.Substring(x, 2), 16))
                    .Aggregate((i, i1) => i ^ i1)
                    .ToString("x") == hex.Substring(hex.Length-2);
}

用法

var hex = "ff03c13d";

Console.WriteLine(Check(hex));

输出

True