C# 如何计算校验和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10947717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:53:56  来源:igfitidea点击:

How to calculate checksum

c#checksum

提问by Rikin Patel

I m developing instrument driver and i want to know how to calculate checksum of frame.

我正在开发仪器驱动程序,我想知道如何计算帧的校验和。

Explanation:

解释:

  1. Expressed by characters [0-9] and [A-F].

  2. Characters beginning from the character after [STX] and until [ETB] or [ETX] (including [ETB] or [ETX]) are added in binary.

  3. The 2-digit numbers, which represent the least significant 8 bits in hexadecimal code, are converted to ASCII characters [0-9] and [A-F].

  4. The most significant digit is stored in CHK1 and the least significant digit in CHK2.

  1. 用字符 [0-9] 和 [AF] 表示。

  2. 从 [STX] 之后的字符开始到 [ETB] 或 [ETX](包括 [ETB] 或 [ETX])的字符以二进制形式添加。

  3. 代表十六进制代码中最低有效 8 位的 2 位数字被转换为 ASCII 字符 [0-9] 和 [AF]。

  4. 最高有效位存储在 CHK1 中,最低有效位存储在 CHK2 中。

i am not getting above 3rd and 4th point.

我没有超过第 3 点和第 4 点。

can any one provide sample code for c#.

谁能提供c#的示例代码。

Please help me.

请帮我。

采纳答案by Rikin Patel

Finally I got answer, here is the code for calculating checksum:

最后我得到了答案,这是计算校验和的代码:

private string CalculateChecksum(string dataToCalculate)
{
    byte[] byteToCalculate = Encoding.ASCII.GetBytes(dataToCalculate);
    int checksum = 0;
    foreach (byte chData in byteToCalculate)
    {
        checksum += chData;
    }
    checksum &= 0xff;
    return checksum.ToString("X2");
}

回答by Barak Rosenfeld

private bool CheckChecksum(string data)
{
   bool isValid =false

   byte[] byteToCalculate = Encoding.ASCII.GetBytes(dataToCalculate);
   int checkSum = 0;
   for ( int i=i i<byteToCalculate.Length;i++)
   {
      checkSum += byteToCalculate[i];
   }
   checksum &= 0xff;

  if (checksum == byteToCalculate[ChecksumPlace]
  {
   return true
  }
  else
  {
  return  false
  }
}

回答by Aleksey

You can do this in one line:

您可以在一行中执行此操作:

return Encoding.ASCII.GetBytes(dataToCalculate).Aggregate((r, n) => r += n).ToString("X2");