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 12Negative 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 FFLearn it first
- Structs, unions, alignment and byte order · Alignment and unaligned access, padding, packing, byte order, unions and bit-fields.
More Structs, unions and memory layout problems
- Remove the padding · Reorder struct members to shrink it from 12 bytes to 8.
- Pack a wire header · Declare a struct that matches a 7-byte protocol header exactly.
- Bits of a float · Return the IEEE 754 bit pattern of a float.
- Overlay a register with bit-fields · Describe an 8-bit control register with a union of a byte and bit-fields.
- Compare two structs · Test two structs for equality without being fooled by padding.
- Describe a tagged union · Format a message whose payload type depends on a tag.
- Return a struct by value · Compute the midpoint of two points and return it as a struct.
- Minimum and maximum of a log · Scan an array of structs and return two results through pointers.
- Predict sizeof · Compute the size of a struct from the sizes of its members.
- Allocate a variable-length packet · Build a heap object with a flexible array member.
- Pack an RGB565 pixel · Squeeze 24-bit colour into the 16-bit format small displays use.
- Compare firmware versions · Order two semantic versions for an update check.
- Convert a header to host order · Fix up the multi-byte fields of a received big-endian header.
- Fix: old payload bytes leak into new packets · A packet is only partly cleared before it is reused.
- Fix: the receiver rejects every header · A header is serialised by copying a struct whose padding does not match the wire format.
- Drone: pack a telemetry packet · Serialise a telemetry struct into an exact 12-byte, high-byte-first packet for the radio.