Simvik

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 03

Empty 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 00

Learn it first

More Protocols, framing and checksums problems