Try Embedded

Protocols, framing and checksums

Checksums, CRCs, byte order, framing and parsing a byte stream.

From bytes to messages

A UART, an SPI bus or a radio delivers a stream of bytes. Turning that stream into messages you can trust takes three steps, and every protocol is some combination of them:

  1. Framing: finding where a message starts and ends.
  2. Integrity: detecting that the message was corrupted on the way.
  3. Encoding: agreeing on what the bytes mean, including byte order.

Byte order on the wire

A protocol document fixes the order in which the bytes of a multi-byte field are sent. Network protocols use big-endian (most significant byte first). Many device protocols, including USB and Bluetooth LE, use little-endian. The CPU's own byte order should never leak into the format.

#include <stdio.h>
#include <stdint.h>

static void put_be16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)(v >> 8); p[1] = (uint8_t)v; }
static void put_le32(uint8_t *p, uint32_t v) {
  for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i));
}
static uint16_t get_be16(const uint8_t *p) { return (uint16_t)((p[0] << 8) | p[1]); }

int main(void) {
  uint8_t frame[6];
  put_be16(frame, 0x1234);
  put_le32(frame + 2, 0xAABBCCDD);
  for (int i = 0; i < 6; i++) printf("%02X ", frame[i]);
  printf("\nfirst field read back: 0x%04X\n", get_be16(frame));
  return 0;
}

Building and reading fields with shifts works on any CPU, at any alignment. Casting the buffer to a struct pointer does not.

Checksums

A checksum is a short value computed from the data and sent with it. The receiver recomputes it and compares.

CheckHowDetectsMisses
Parity bitXOR of the bitsAny odd number of flipped bitsAny even number
XOR of bytesXOR every byteAny single-bit errorTwo errors in the same bit position; reordered bytes
Additive (sum, two's complement)Sum of the bytes modulo 256Any single-bit errorReordered bytes; errors that cancel
CRCPolynomial divisionAll burst errors up to its width, and almost everything elseAbout 1 in 2^N random corruptions
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

static uint8_t xor_checksum(const uint8_t *d, size_t n) {
  uint8_t c = 0;
  while (n--) c ^= *d++;
  return c;
}

static uint8_t sum_checksum(const uint8_t *d, size_t n) {
  uint8_t s = 0;
  while (n--) s = (uint8_t)(s + *d++);
  return (uint8_t)(0u - s);          // chosen so that data plus checksum sums to 0
}

int main(void) {
  const uint8_t good[] = { 0x10, 0x20, 0x30 };
  const uint8_t swapped[] = { 0x20, 0x10, 0x30 };      // two bytes exchanged in transit
  printf("xor: %02X vs %02X\n", xor_checksum(good, 3), xor_checksum(swapped, 3));
  printf("sum: %02X vs %02X\n", sum_checksum(good, 3), sum_checksum(swapped, 3));
  return 0;
}

Both simple checksums give the same result for the swapped data, so the error goes unnoticed. That is why real links use a CRC.

CRC

A CRC treats the message as one long binary number and computes the remainder of dividing it by a fixed polynomial, using XOR in place of subtraction. In code it is a shift register: for each bit, shift, and XOR in the polynomial whenever a 1 falls out.

A CRC is not one algorithm but a family. Two implementations agree only if all of these match:

ParameterMeaningCRC-8 (SMBus)CRC-16 (Modbus)
WidthBits in the result816
PolynomialThe divisor0x070x8005, used reflected as 0xA001
Initial valueStarting contents of the register0x000xFFFF
ReflectionWhether bits are processed LSB firstnoyes
Final XORApplied to the result0x000x0000
Check valueCRC of the ASCII text 1234567890xF40x4B37
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

static uint8_t crc8(const uint8_t *data, size_t n) {
  uint8_t crc = 0x00;
  for (size_t i = 0; i < n; i++) {
    crc ^= data[i];
    for (int bit = 0; bit < 8; bit++) {
      crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x07) : (uint8_t)(crc << 1);
    }
  }
  return crc;
}

int main(void) {
  const uint8_t msg[] = "123456789";
  uint8_t crc = crc8(msg, 9);
  printf("CRC-8 of \"123456789\" = 0x%02X\n", crc);

  uint8_t framed[10];
  for (int i = 0; i < 9; i++) framed[i] = msg[i];
  framed[9] = crc;
  printf("CRC over data plus its CRC = 0x%02X\n", crc8(framed, 10));
  return 0;
}

Two properties to remember. Every published CRC has a check value for the input 123456789; if yours matches, the parameters are right. And running the CRC over the data followed by its own CRC gives a constant (zero for these variants), so a receiver can validate a whole frame in a single pass.

The bit-by-bit loop costs eight iterations per byte. A 256-entry lookup table reduces that to one XOR and one table read per byte, at the price of 256 or 512 bytes of flash. Many MCUs also have a CRC peripheral.

Framing

The receiver needs to know where a message begins. These are the common schemes.

SchemeExampleStrengthWeakness
Delimiter charactersNMEA: $ ... *hh\r\nHuman-readable, self-synchronisingOnly for text
Start byte and length7E len payload checksumSimple and compactA start byte inside the payload can cause a false sync
Byte stuffingSLIP, HDLC, PPPDelimiter never appears in the dataWorst-case size doubles
COBSMany modern serial linksAt most 1 byte of overhead per 254Slightly more code
Silence between framesModbus RTU (3.5 character times)No overhead bytesNeeds accurate timing

Byte stuffing

If a reserved byte appears in the data, replace it with an escape sequence. SLIP uses 0xC0 as the end marker and 0xDB as the escape:

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

#define END 0xC0
#define ESC 0xDB

static size_t slip_encode(const uint8_t *in, size_t n, uint8_t *out) {
  size_t w = 0;
  for (size_t i = 0; i < n; i++) {
    if (in[i] == END)      { out[w++] = ESC; out[w++] = 0xDC; }
    else if (in[i] == ESC) { out[w++] = ESC; out[w++] = 0xDD; }
    else out[w++] = in[i];
  }
  out[w++] = END;
  return w;
}

int main(void) {
  const uint8_t packet[] = { 0x01, 0xC0, 0x02, 0xDB };
  uint8_t out[10];
  size_t n = slip_encode(packet, sizeof packet, out);
  for (size_t i = 0; i < n; i++) printf("%02X ", out[i]);
  printf("\n");
  return 0;
}

Parsing a stream one byte at a time

Bytes arrive one at a time, usually in an interrupt, and a frame may be split across any number of them. A parser therefore cannot be written as "read the header, then read the payload". It must be a state machine that takes one byte, updates its state and returns.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#define MAX_PAYLOAD 8
typedef enum { WAIT_START, WAIT_LEN, READ_PAYLOAD, WAIT_CHECKSUM } state_t;
typedef struct { state_t state; uint8_t len, index, checksum, payload[MAX_PAYLOAD]; } parser_t;

static bool feed(parser_t *p, uint8_t byte) {
  switch (p->state) {
    case WAIT_START:
      if (byte == 0x7E) p->state = WAIT_LEN;
      break;
    case WAIT_LEN:
      if (byte > MAX_PAYLOAD) { p->state = WAIT_START; break; }   // never trust a length
      p->len = byte; p->index = 0; p->checksum = byte;
      p->state = byte ? READ_PAYLOAD : WAIT_CHECKSUM;
      break;
    case READ_PAYLOAD:
      p->payload[p->index++] = byte;
      p->checksum ^= byte;
      if (p->index == p->len) p->state = WAIT_CHECKSUM;
      break;
    case WAIT_CHECKSUM:
      p->state = WAIT_START;
      return byte == p->checksum;
  }
  return false;
}

int main(void) {
  parser_t p = { 0 };
  const uint8_t stream[] = { 0xFF, 0x7E, 0x02, 0xAA, 0xBB, 0x13, 0x7E, 0x01, 0x55, 0x00 };
  for (unsigned i = 0; i < sizeof stream; i++) {
    if (feed(&p, stream[i])) printf("frame of %u bytes accepted at stream byte %u\n", p.len, i);
  }
  printf("the second frame had a bad checksum and was dropped\n");
  return 0;
}

Notice what protects the buffer: the length is checked against MAX_PAYLOAD before a single payload byte is stored. A length field taken from the wire and used without a bounds check is the most common remote memory-corruption bug in embedded software.

A production parser adds a timeout that returns to WAIT_START when a frame stalls, so that one lost byte does not swallow the frame that follows.

The serial buses in one table

UARTI2CSPI
WiresTX, RXSDA, SCLSCK, MOSI, MISO, one CS per device
ClockNone; both sides agree on a baud rateController drives SCLController drives SCK
AddressingNone; point to point7-bit address in the first byteChip-select line
Typical speed9600 to 1 Mbit/s100 kbit/s, 400 kbit/s1 to 50 Mbit/s
Error detectionOptional parity; framing errorsACK/NACK per byteNone
Watch out forBaud mismatch above about 2 percentMissing pull-ups; shifted vs unshifted addressClock polarity and phase (the four modes)

A UART frame is a start bit (low), the data bits least significant first, an optional parity bit and a stop bit (high). The first byte of an I2C transfer is the 7-bit address shifted left by one, with the read/write flag in bit 0.

Common mistakes

  • Sending a struct with memcpy and calling it a protocol.
  • Trusting a received length before checking it against the buffer.
  • Computing a CRC with the right polynomial and the wrong initial value or bit order.
  • Sending the two bytes of a 16-bit CRC in the wrong order.
  • A parser with no way back to its idle state after a damaged frame.

Interview question: You get the wrong CRC for a known-good message. What do you check?

Answer: Run the algorithm on the ASCII string 123456789 and compare with the published check value for the variant. If it differs, one of the parameters is wrong: the polynomial (and whether it is the reflected form), the initial value, whether input and output are bit-reflected, or the final XOR. If the check value matches, the problem is in which bytes are covered or in the byte order in which the CRC is transmitted.

Interview question: Why is a start byte alone not enough for reliable framing?

Answer: The same byte value can occur inside the payload, so a receiver that joins mid-stream, or loses a byte, can lock on to a false start. Reliable schemes make the delimiter impossible in the data (byte stuffing or COBS), or combine a start byte with a length and a strong checksum and resynchronise when the check fails. A timeout is also needed, so a frame that never completes does not block the parser.

In the product: a solar inverter

The monitoring box reads the inverter's status frame and must never act on a damaged one. The checksum decides, before any field is used.

#include <stdio.h>
#include <stdint.h>

int main(void) {
  uint8_t frame[6] = { 0xAA, 0x0B, 0xB8, 0x2D, 0x01, 0x00 };   // start, power (2 bytes), temp, status, checksum
  for (int i = 1; i < 5; i++) frame[5] ^= frame[i];             // the sender's checksum
  frame[2] ^= 0x10;                                             // noise flips one bit on the way

  uint8_t x = 0;
  for (int i = 1; i < 5; i++) x ^= frame[i];
  if (x != frame[5]) printf("checksum mismatch: frame dropped\n");
  else printf("power: %u W\n", frame[1] << 8 | frame[2]);
  return 0;
}

Build it: telemetry packets the server can trust

This is step 4 of the module project. Every few seconds the tracker sends its state to the fleet server through a cellular modem on a UART. Bytes on that link can be lost or corrupted, so each message goes in a frame that the other end can find, check and reject.

Lab: Build and parse telemetry frames with a CRC

The frame format agreed with the server team:

BytesContents
2sync: 0xAA, 0x55
1message type
1payload length, 0 to 32
npayload
1CRC-8 of the type, length and payload bytes (not the sync)

The CRC is CRC-8 with polynomial 0x07, initial value 0x00: for each byte, XOR it into the CRC, then 8 times shift the CRC left one bit, XOR-ing in 0x07 whenever the bit shifted out was 1.

  • crc8(data, n) computes it.
  • frame_build(type, payload, len, out) writes a whole frame into out and returns its length, or 0 if len is over 32.
  • frame_parse(in, n, type, payload) checks a received frame: n must match the length byte exactly, the sync must be right and the CRC must match. It returns the payload length, with the type and payload filled in, or -1 for any frame it rejects. A rejected frame must never be acted on.

Going deeper

Interview question: Your inverter monitor shows a power spike that never happened. How do you find the cause?

Answer: Decide first whether the inverter sent it or the link corrupted it: log raw frames with timestamps and see whether the spike's frame passed the integrity check. A weak checksum (like an 8-bit XOR) can pass two flipped bits, so move to a CRC; check framing too, since a frame split across two reads can be misparsed if the parser does not resynchronise. If the inverter really sent it, the fix belongs there, but the monitor should also reject physically impossible values.

Interview question: What is byte stuffing, and how does COBS avoid its worst case?

Answer: Framing a byte stream with a delimiter requires escaping any occurrence of that delimiter in the data (byte stuffing, as in SLIP or HDLC), which can double the size in the worst case. COBS (consistent overhead byte stuffing) replaces each zero with the distance to the next zero so the encoded data contains no zeros at all, letting 0x00 be the frame delimiter with a worst-case overhead of one byte per 254. It makes resynchronisation after an error trivial.

Interview question: Why is a CRC better than a simple checksum?

Answer: A sum of bytes misses many common errors: reordered bytes, two compensating errors, and many burst errors. A CRC treats the data as a polynomial and divides by a generator polynomial; well-chosen ones detect all single and double bit errors, all odd numbers of bit errors (for suitable polynomials) and all burst errors shorter than the CRC width. It is cheap with a lookup table or a hardware CRC unit.

Explain it: In your own words, explain how a receiver should parse a byte stream into messages robustly.

Answer: Run a small state machine fed one byte at a time: wait for the start marker, read the header including the length, check the length is within the maximum allowed, collect exactly that many bytes, then check the CRC. If anything is wrong, such as an impossible length, a bad CRC or a timeout between bytes, discard the partial message and return to hunting for the next start marker rather than trusting the data. Only fully validated messages are passed on.