gpt4 book ai didi

c# - 如何使用数据结构中所有字节的 8 位加法计算校验和

转载 作者:行者123 更新时间:2023-11-30 13:10:43 25 4
gpt4 key购买 nike

我需要从字节数组计算校验和。它是一些串口数据包。我只有这段文字:

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

8位加法怎么做?

在 C# 中需要它。

最佳答案

直接加法?好吧,您可以很容易地遍历所有字节:

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

或者,使用 LINQ:

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

我正在使用 long 来避免在长流上溢出 - 我假设它会小于 255 字节 :) 实际上你可能会可以使用 int 而不是 long

关于c# - 如何使用数据结构中所有字节的 8 位加法计算校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4648130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com