Calculate checksum for Laboratory Information System (LIS) frames

喜欢而已 提交于 2020-08-17 20:03:14

问题


I'm developing an instrument driver for a Laboratory Information System. I want to know how to calculate the checksum of a frame.

Explanation of the checksum algorithm:

  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.

I am not getting the 3rd and 4th points above.

This is a sample frame:

<STX>2Q|1|2^1||||20011001153000<CR><ETX><CHK1><CHK2><CR><LF>

What is the value of CHK1 and CHK2? How do I implement the given algorithm in C#?


回答1:


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



回答2:


You can do this in one line:

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



回答3:


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


来源:https://stackoverflow.com/questions/10947717/calculate-checksum-for-laboratory-information-system-lis-frames

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!