Bit-Packed Struct Serializer

Medium C++ Packaging Asked at Broadcom
Solve this problem

Serialise a telemetry record into the smallest possible wire format by packing fields at bit granularity, then deserialise it back losslessly.

Constraints

  • Fields: 12-bit temperature, 10-bit pressure, 6-bit status.
  • Total must fit in exactly 4 bytes.
  • Byte order on the wire is big-endian.
  • Round-trip must be exact for every legal field value.
  • No compiler bitfields - layout must be explicit and portable.
  • No allocation.
Starter codeC++
1#include <cstdint>2#include <array>3 4struct Telemetry { uint16_t temperature; uint16_t pressure; uint8_t status; };5 6std::array<uint8_t, 4> pack(const Telemetry& t);7Telemetry unpack(const std::array<uint8_t, 4>& bytes);