Search code examples
c#returnbytexorcrc

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


ff03c1 3d

how to xor this string and get checksum 3d ?

the scenario is:

i get string like ff03c13d. (there are other models with longer lengths). and i should check crc in hex;

like this:

ff xor 03 xor c1 and if result equal the last two characters or the last byte (like 3d) return True.

thanks for your help


Solution

  • Linq, 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);
    

    Full Demo Here

    Method

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

    Usage

    var hex = "ff03c13d";
    
    Console.WriteLine(Check(hex));
    

    Output

    True