Skip to content

Instantly share code, notes, and snippets.

@MattWoodhead
Created February 17, 2018 13:56
Show Gist options
  • Save MattWoodhead/0bc2b3066796e19a3a350689b43b50ab to your computer and use it in GitHub Desktop.
Save MattWoodhead/0bc2b3066796e19a3a350689b43b50ab to your computer and use it in GitHub Desktop.
Concise Python 3 function for validating an NMEA string using its included checksum
import operator
from functools import reduce
def nmea_checksum(sentence: str):
"""
This function checks the validity of an NMEA string using it's checksum
"""
sentence = sentence.strip("$\n")
nmeadata, checksum = sentence.split("*", 1)
calculated_checksum = reduce(operator.xor, (ord(s) for s in nmeadata), 0)
if int(checksum, base=16) == calculated_checksum:
return nmeadata
else:
raise ValueError("The NMEA data does not match it's checksum")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment