Search code examples
c#design-patternschecksumxor

Easy way to generate XOR checksum on a stream?


In C# is there an easy way to generate an XOR checksum on a MemoryStream (binary) excluding the first, and last two, bytes?

Also, is it easier to extend the BinaryWriter and do it as the Stream is written?


Solution

  • You can use LINQ to get the answer:

    var checksum = memStream
        .GetBuffer() // Get the underlying byte array
        .Skip(1)     // Skip the first byte
        .Take(memStream.Length-3) // One for the beginning, two more for the end
        .Aggregate(0, (p,v) => p ^ v); // XOR the accumulated value and the next byte