Simvik

Serialise a struct

Write a struct to a byte buffer in a defined, portable format. A medium embedded C problem (Structs, unions and memory layout), run and graded in the browser.

medium · Structs, unions and memory layout · serialisation · endianness

Send status_t over a link as exactly 7 bytes, little-endian, with no padding:

  • byte 0: id
  • bytes 1..2: voltage_mv, low byte first
  • bytes 3..6: position, low byte first

Write those bytes to out and return the number of bytes written.

Starter code

size_t status_pack(const status_t *s, uint8_t *out) {
  // Write 7 bytes in the documented order. sizeof(status_t) is 8, so memcpy is not the answer.
  return 0;
}

Example tests

Positive values

status_t s = { 0x07, 3300, 0x12345678 };
uint8_t out[7];
size_t n = status_pack(&s, out);
printf("%u:", (unsigned)n);
for (size_t i = 0; i < 7; i++) printf(" %02X", out[i]);
printf("\n");

Expected output:

7: 07 E4 0C 78 56 34 12

Negative position

status_t s = { 0x01, 1, -2 };
uint8_t out[7];
size_t n = status_pack(&s, out);
printf("%u:", (unsigned)n);
for (size_t i = 0; i < 7; i++) printf(" %02X", out[i]);
printf("\n");

Expected output:

7: 01 01 00 FE FF FF FF

Learn it first

More Structs, unions and memory layout problems