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:
0xC0in the data becomes0xDB 0xDC0xDBin the data becomes0xDB 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 C0An 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 C0Learn it first
- Protocols, framing and checksums · Checksums, CRCs, byte order, framing and parsing a byte stream.
More Protocols, framing and checksums problems
- XOR checksum · Compute the XOR of every byte in a buffer.
- Two's-complement checksum · Compute the checksum byte of an Intel HEX record.
- CRC-8 · Implement a bitwise CRC-8 with polynomial 0x07.
- CRC-16 for Modbus · Implement the reflected CRC-16 used by Modbus RTU.
- Read a big-endian word · Assemble a 32-bit value from four bytes of a packet.
- I2C address byte · Build the first byte of an I2C transfer.
- BCD conversion · Convert between binary-coded decimal and binary.
- Build a UART frame · Assemble the bits a UART sends for one byte with parity.
- Build a framed message · Wrap a payload with a start byte, a length and a checksum.
- Variable-length integer · Encode a 32-bit value in as few bytes as it needs.
- Validate an NMEA sentence · Check the checksum of a GPS sentence.
- Byte-stream frame parser · Reassemble frames from a byte stream one byte at a time.
- COBS encoding · Remove every zero byte from a packet with one byte of overhead.
- Fix: the bootloader hangs on large chunks · A loop counter is too narrow for the length it counts to.
- Fix: frame lengths come out 256 times too big · A big-endian length field is decoded as little-endian.
- Reliable delivery over a lossy link · Stop-and-wait with a sequence bit, acknowledgements, a retransmit timer and duplicate detection.
- Solar inverter: decode a status frame · Check a frame from the inverter and decode its power, voltage and temperature.