Build a framed message
Wrap a payload with a start byte, a length and a checksum. A medium embedded C problem (Protocols, framing and checksums), run and graded in the browser.
medium · Protocols, framing and checksums · framing · checksum
A serial protocol sends each message as:
0x7E, the start byte- the payload length, one byte
- the payload
- a checksum: the XOR of the length byte and every payload byte
Write the frame for payload (len bytes) into out and return the total number of bytes written.
Starter code
size_t frame_build(const uint8_t *payload, uint8_t len, uint8_t *out) {
// 7E, len, payload..., checksum
return 0;
}Example tests
Three payload bytes
const uint8_t p[] = { 0x01, 0x02, 0x03 };
uint8_t out[6];
size_t n = frame_build(p, 3, out);
printf("%u:", (unsigned)n);
for (size_t i = 0; i < n; i++) printf(" %02X", out[i]);
printf("\n");Expected output:
6: 7E 03 01 02 03 03Empty payload
uint8_t out[3];
size_t n = frame_build(NULL, 0, out);
printf("%u:", (unsigned)n);
for (size_t i = 0; i < n; i++) printf(" %02X", out[i]);
printf("\n");Expected output:
3: 7E 00 00Learn 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.
- SLIP byte stuffing · Escape reserved bytes so a frame delimiter is unambiguous.
- 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.