Validate an NMEA Sentence
GPS modules output NMEA 0183 sentences like:
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
The checksum is the XOR of every character between $ and * (exclusive), written as two hex digits after *. Write bool nmea_valid(const char *s) that returns true only if the sentence starts with $, contains * followed by exactly two hex digits (upper or lower case) and an optional \r\n, and the checksum matches.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Write a small helper that converts one hex character to its value or returns -1.
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
static int hexval(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return -1;
}
bool nmea_valid(const char *s)
{
if (*s++ != '$') return false;
uint8_t sum = 0;
while (*s && *s != '*') sum ^= (uint8_t)*s++;
if (*s++ != '*') return false;
int hi = hexval(s[0]);
if (hi < 0) return false;
int lo = hexval(s[1]);
if (lo < 0) return false;
s += 2;
if (s[0] == '\r' && s[1] == '\n') s += 2;
if (*s != '\0') return false;
return sum == (uint8_t)(hi << 4 | lo);
}
The checks are ordered so the code never reads past the terminator: s[1] is only examined after s[0] was a valid hex digit, which means it was not '\0'. Parsing defensively matters because GPS data arrives over a noisy link and often starts mid-sentence.
In a real receiver you would accumulate characters from the UART ring buffer into a line buffer of bounded size (NMEA allows 82 characters), validate, and then split fields on commas.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(nmea_valid("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"));
CHECK(nmea_valid("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47\r\n"));
CHECK(!nmea_valid("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*48"));
CHECK(nmea_valid("$A*41"));
CHECK(nmea_valid("$a*61"));
CHECK(!nmea_valid("GPGGA*00"));
CHECK(!nmea_valid("$A*4"));
CHECK(!nmea_valid("$A41"));
CHECK(!nmea_valid("$A*4G"));
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}