How to calculate a checksum using 8-bit addition of all bytes in a data structure

I need to calculate a checksum from an array of bytes. Its several serial port packets. I have only this text:

The checksum is calculated using the 8-bit addition of all bytes in the data structure. Do not count threads (1 byte).

How to make an 8-bit add-on?

You need to use it in C #.

+3
source share
3 answers

Direct addition? Well, you can quite easily iterate over all bytes:

public static byte ComputeAdditionChecksum(byte[] data)
{
    byte sum = 0;
    unchecked // Let overflow occur without exceptions
    {
        foreach (byte b in data)
        {
            sum += b;
        }
    }
    return sum;
}

Alternatively using LINQ:

public static byte ComputeAdditionChecksum(byte[] data)
{
    long longSum = data.Sum(x => (long) x);
    return unchecked ((byte) longSum);
}

long, - , 2 55 :) , , int long.

+16

LINQ

public static byte CheckSum(byte[] array)
{
     return array.Aggregate<byte, byte>(0, (current, b) => (byte) ((current + b) & 0xff));
}
+2

In C #, read the data into an array of byte types and add all the bytes to a separate byte variable to get the result of the checksum.

0
source

Source: https://habr.com/ru/post/1784549/


All Articles