Simvik

SLIP byte stuffing

Escape reserved bytes so a frame delimiter is unambiguous. A medium embedded C problem (Protocols, framing and checksums), run and graded in the browser.

medium · Protocols, framing and checksums · framing · byte-stuffing

SLIP marks the end of a packet with 0xC0 (END). Data bytes that happen to equal a reserved value are replaced by two-byte escape sequences:

  • 0xC0 in the data becomes 0xDB 0xDC
  • 0xDB in the data becomes 0xDB 0xDD

Encode the n bytes at in into out, append one END byte and return the number of bytes written. out is large enough.

Starter code

size_t slip_encode(const uint8_t *in, size_t n, uint8_t *out) {
  // Escape 0xC0 and 0xDB, then terminate with 0xC0.
  return 0;
}

Example tests

An END byte inside the data

const uint8_t in[] = { 0x01, 0xC0, 0x02 };
uint8_t out[8];
size_t n = slip_encode(in, 3, out);
for (size_t i = 0; i < n; i++) printf("%02X ", out[i]);
printf("\n");

Expected output:

01 DB DC 02 C0

An ESC byte inside the data

const uint8_t in[] = { 0xDB };
uint8_t out[4];
size_t n = slip_encode(in, 1, out);
for (size_t i = 0; i < n; i++) printf("%02X ", out[i]);
printf("\n");

Expected output:

DB DD C0

Learn it first

More Protocols, framing and checksums problems