Как разделить символ в двоичном виде и контрольную сумму их c # - PullRequest
0 голосов
/ 12 января 2019
ff03c1 3d

как исправить эту строку и получить контрольную сумму 3d?

сценарий:

я получаю строку как ff03c13d. (есть другие модели с большей длиной). и я должен проверить CRC в шестнадцатеричном;

как это:

ff xor 03 xor c1 и, если результат равен двум последним символам или последнему байту (например, 3d), возвращает True.

спасибо за вашу помощь

Ответы [ 3 ]

0 голосов
/ 12 января 2019

Следующая функция может сделать XOR вашей шестнадцатеричной строки

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

Выход:

enter image description here

0 голосов
/ 12 января 2019

Линк, Where, Select, Aggregate, ToString

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

Полная демонстрация здесь

Метод

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
0 голосов
/ 12 января 2019

Вы можете проанализировать значения с помощью int.Parse с NumberStyles.HexNumber , чтобы извлечь значения из строки, XOR частей, которые нужны XOR ing (каждый *) 1007 * значение в string.Length -2) и сравните с CRC, представленным последними 2 Hex символами в строке.

Примерно так:

Используя предоставленную строку:

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