Overlay a register with bit-fields
Describe an 8-bit control register with a union of a byte and bit-fields. A medium embedded C problem (Structs, unions and memory layout), run and graded in…
medium · Structs, unions and memory layout · bit-fields · unions
A control register has this layout, from bit 0 upwards:
- bit 0:
enable - bits 3..1:
mode - bits 5..4:
prescaler - bit 6: reserved
- bit 7:
irq
Complete ctrl_reg_t so that bits.enable, bits.mode, bits.prescaler and bits.irq access those fields and raw accesses the whole byte.
Starter code
typedef union {
uint8_t raw;
struct {
uint8_t enable : 1; // bit 0
// mode: bits 3..1, prescaler: bits 5..4, bit 6 reserved, irq: bit 7
} bits;
} ctrl_reg_t;Example tests
Writing fields changes the raw byte
ctrl_reg_t r = { .raw = 0 };
r.bits.enable = 1;
r.bits.mode = 5;
printf("0x%02X\n", r.raw);Expected output:
0x0BReading fields from a raw byte
ctrl_reg_t r = { .raw = 0xA5 };
printf("%u %u %u %u\n", r.bits.enable, r.bits.mode, r.bits.prescaler, r.bits.irq);Expected output:
1 2 2 1Learn 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.
- 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.
- Serialise a struct · Write a struct to a byte buffer in a defined, portable format.
- 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.