Search code examples
javagpschecksumnmea

NMEA checksum calculation


I have a problem with calculating the checksum for NMEA sentences. I am using the following java code:

private static String getSum(String in) {
    int checksum = 0;
    if (in.startsWith("$")) {
        in = in.substring(1, in.length());
    }

    int end = in.indexOf('*');
    if (end == -1)
        end = in.length();
    for (int i = 0; i < end; i++) {
        checksum = checksum ^ in.charAt(i);
    }
    String hex = Integer.toHexString(checksum);
    if (hex.length() == 1)
        hex = "0" + hex;
    return hex.toUpperCase();
}

This code is similar to many other examples around the internet and everything works fine until I try a sentence like this..

$PSRF101,-2686700,-4304200,3851624,96000,497260,921,12,3*1C

This sentence is from the NMEA Reference Manual and so I assume the checksum will be correct. But when I calculate it, I get *2F as the checksum and not 1C.

I think this is because of the negative values in the sentence, but I have no clue how to deal with them. Does anybody have a suggestion?


Solution

  • The difference of the assumed and the calculated checksums equals to omitting (or having an extra character '3'); so I'd be tempted to believe in error in the NMEA Reference Manual.

    You can try some online NMEA calculator to verify the results.
    e.g. http://www.hhhh.org/wiml/proj/nmeaxor.html