Calculate a XOR checksum in c++ (for Arduino)
You can use this to either decode a string you made on your own, but this is genarlly also used for NMEA strings, that are used for GPS. So you can decode a checksum for a GPS sentence and check it. Also, see the code in C# for this if you want to interface like i have used this for.
The sentence generally looks like this
$$blablablablabliebloe*
then you calculate the checksum from the above to produce something like
$$blablablabalbablab*6C
in which that 6C is then the checkum. This way you make sure your info is correct. better is even to use a CRC16 checksum, but this code is fairly easy and robust. You can never look past code you don’t understand.
// Validates the checksum on an (for instance NMEA) string
// Returns 1 on valid checksum, 0 otherwise
int validateChecksum(void) {
char gotSum[2];
gotSum[0] = buffer[strlen(buffer) - 2];
gotSum[1] = buffer[strlen(buffer) - 1];
// Check that the checksums match up
if ((16 * atoh(gotSum[0])) + atoh(gotSum[1]) == getCheckSum(buffer)) return 1;
else return 0;
}
// Calculates the checksum for a given string
// returns as integer
int getCheckSum(char *string) {
int i;
int XOR;
int c;
// Calculate checksum ignoring any $'s in the string
for (XOR = 0, i = 0; i < strlen(string); i++) {
c = (unsigned char)string[i];
if (c == '*') break;
if (c != '$') XOR ^= c;
}
return XOR;
}
[…] [Checksum] XOR (cpp) […]