Reputation: 69
I need to calculate the Checksum for an analytical laboratory instrument. I have this example:
I am using the method taken from this post: Calculate checksum for Laboratory Information System (LIS) frames
This is the code from the example that calculates the 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");
}
And this is the code I used to do the image test:
string cStringStx = ((char)02).ToString();
string cStringEtx = ((char)03).ToString();
string cStx = CalculateChecksum(cStringStx);//Result: 02
string c1 = CalculateChecksum("1");//Result: 31
string cT = CalculateChecksum("T");//Result: 54
string cE = CalculateChecksum("e");//Result: 65
string cS = CalculateChecksum("s");//Result: 73
string cT2 = CalculateChecksum("t");//Result: 74
string cEtx = CalculateChecksum(cStringEtx);//Result: 03
int nSum = Convert.ToInt16(cStx) +
Convert.ToInt16(c1) +
Convert.ToInt16(cT) +
Convert.ToInt16(cE) +
Convert.ToInt16(cS) +
Convert.ToInt16(cT2) +
Convert.ToInt16(cEtx);//Result: 302
string cTot = CalculateChecksum(cStx + c1 + cT + cE + cS + cT2 + cEtx);//Result: D2
The checksum of the individual strings is correct, but the sum is not. cTot should be D4, instead it is D2. What am I doing wrong?
Upvotes: 0
Views: 208
Reputation: 186668
Well, it seems that you want to skip the initial [STX]
character (\u0002
) while summing all the others. You can do it with a help of Linq:
using System.Linq;
...
private static int CheckSum(string value) {
return value == null
? 0
: value.SkipWhile(c => c == 2).Sum(c => c) & 0xFF;
}
Demo:
string test = "\u00021Test\u0003";
int sum = CheckSum(test);
Console.Write(sum.ToString("X2"));
Outcome:
D4
Upvotes: 2