Calculate checksum for Laboratory Information System (LIS) frames
Solution 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");
}
Solution 2
You can do this in one line:
return Encoding.ASCII.GetBytes(dataToCalculate).Aggregate((r, n) => r += n).ToString("X2");
Rikin Patel
Updated on July 20, 2020Comments
-
Rikin Patel almost 4 years
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:
-
Expressed by characters [0-9] and [A-F].
-
Characters beginning from the character after [STX] and until [ETB] or [ETX] (including [ETB] or [ETX]) are added in binary.
-
The 2-digit numbers, which represent the least significant 8 bits in hexadecimal code, are converted to ASCII characters [0-9] and [A-F].
-
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
andCHK2
? How do I implement the given algorithm in C#?-
Rikin Patel almost 12 yearsi m confusion in what is final ans. it is 4 digit or 2 digit.and i am not getting what i will do after sum of all byte.
-
Rikin Patel almost 12 yearsthis is sample frame : <STX>2Q|1|2^1||||20011001153000<CR><ETX><CHK1><CHK2><CR><LF> and i want to know what is value of chk1 and chk2 and i am new in this so i m totally blank about how to calculate checksum.
-
Collin almost 12 yearsLike we talked about in chat, we need to know what kind of checksum algorithm the instrument is expecting you to use. Is it a CRC, Fletcher, or something else?
-
Rikin Patel almost 12 years@Collin this things does not disclose in documentation of instrument just given above explanation.
-
janw almost 4 yearsNote: This question has also been posted on Software Engineering SE. I have edited this question to include some context.
-
-
Rikin Patel almost 7 yearsPls, read Que. I want checksum value of given string but your ans. returning the boolean value.
-
Rikin Patel over 4 yearsyou are missing "checksum &= 0xff"
-
Aleksey over 4 yearsNo, this is not needed as the type of
r
isbyte
, it can't go over two letters -
PauLEffect over 4 yearsLet's assume that byte[3] = {0,0,0} gets sent instead of your actual buffer. The checksum is 0, and it's valid... you ought to check for that case, among other things. It's a really weak checksum algorithm (no offense).