I feel this is a stupid question but i cant get this to work so please bear with me. I want to calculate a simple checksum to check if the data i received over serial and stored in a QByteArray is not corrupt(or is correct).
the packet format of the data i am receiving is like this: // Packet format: // //|CHAR1<1>|CHAR2<1>|CLASS<1>|ID<1>|LENGTH<2>|PAYLOAD|CK_A<1>|CK_B<1>|
// <--------------------- 4 ---------------------------->|
// <--------------------------------------- 6 ----------------------------->|
// <--------------------------------------- 6 + length -------------------------------->|
//<---------------------------------------------------------8+length------------------------------------------->|
There are two check sums CK_A and CK_B. Each is a single byte long.The checksum Algorithm is the 8-Bit Fletcher Algorithm:
CK_A = 0;
CK_B = 0;
for(i=0,i<n,i++){
CK_A = CK_A + Buffer[i];
CK_B = CK_B + CK_A;
}
I am having trouble with adding up the hex values stored in the QByteArray. This is the code I have written.It ads up the values but they are not correct and the code is messy.
for(int I = 4; I < length + 4; I+=2){
tempHex[0] = serialData[I];
tempHex[1] = serialData[I + 1];
tempDec=tempHex.toInt();
CheckSum_A_int = (CheckSum_A_int + tempDec);
CheckSum_A_int &= 0xFF;
CheckSum_B_int = (CheckSum_B_int + CheckSum_A_int);
CheckSum_A_int &= 0xFF;
CK_A = CheckSum_A_int;
CK_B = CheckSum_B_int;
CK_A = CK_A.toLatin1().toHex();
CK_B = CK_B.toLatin1().toHex();
}
Does anybody know the correct or better way to do this. Or can someone please explain to me how hex values is a QByteArray can be added up? This is a sample of the data : "b56201241400009b4209d25e02009be0f8ffcc020407140d0000bd33". CK_A should be "bd" and CK_B shoud be "33".
Thanks a lot for your patience. Regards