[Checksum] XOR (cpp)

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


then you calculate the checksum from the above to produce something like


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;

One response

24 03 2011
More code released « Tim Zaman

[…] [Checksum] XOR (cpp) […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: