开发者

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

开发者 https://www.devze.com 2023-02-03 05:42 出处:网络
I need to calculate checksum from byte array. Its some serial port pac开发者_如何学运维ket. I have just this text:

I need to calculate checksum from byte array. Its some serial port pac开发者_如何学运维ket. I have just this text:

Checksum is calculated using 8-bit addition of all bytes in the data structure. Overflows are not taken into account (1 byte).

How do 8-bit addition?

Need it in C#.


Straight addition? Well, you could iterate over all the bytes pretty easily:

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

I'm using long to avoid overflowing on a long stream - I'm assuming it will be less than 255 bytes :) In practice you'd probably be fine using int instead of long.


LINQ Solution

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


In C#, read data into byte type array, and add all bytes to a seperate byte variable to get checksum result.

0

精彩评论

暂无评论...
验证码 换一张
取 消