Code to test u-blox Binary GPS Packet Checksum

Here’s something random for a Thursday, the following is some simple C++ code for checking the checksum of a u-blox binary GPS packet, for some reason we get quite a few packet data errors, so it turns out that it is important to check the checksum!

There must be an unwritten (or written?) software engineering rule which states that you should always check a checksum if one’s provided??!?

Note: Make sure to pass only complete packets to this function, it assumes it has everything to work with!

//
//
bool is_checksum_ok(unsigned char* buf) {
	// Packet format:
	// SYNC<1> SYNC<1> CLASS<1> ID<1> LENGTH<2> PAYLOAD CHKA<1> CHKB<1>
	// --------------- 4 ----------->|
	// --------------- 6 --------------------->|
	// --------------- 6 + length ---------------------------->|
	// Payload length field is little-endian (bless)
	unsigned short length = buf[5] << 8 | buf[4];
	unsigned char a = 0;
	unsigned char b = 0;
	// We calculate the checksum over the entire packet _except_
	// for the 2 bytes at the beginning and the 2 checksum bytes at
	// the end.
	for (unsigned short i = 2; i < 6 + length; ++i) {
		a += buf[i];
		b += a;
	}
	// Pull out checksum bytes
	unsigned char ra = buf[6 + length];
	unsigned char rb = buf[6 + 1 + length];
	// and compare
	return a = ra && b == rb;
}
//
//