5.1.23 · D3C Programming

Worked examples — Bit fields in structs

2,740 words12 min readBack to topic

Parent: Bit Fields in Structs

This page walks the whole zoo of bit-field situations. Before we solve, we map the terrain, so you can see that we left nothing out.


The scenario matrix

Every bit-field puzzle you will ever meet falls into one of the cells below. We name the cell, then later solve at least one example that lands squarely in it.

# Case class What makes it tricky Covered by
A Choosing a width pick smallest with needed values Ex 1
B Unsigned overflow (wrap) value too big → keep low bits Ex 2
C Signed field, positive value top bit is a sign, not a value Ex 3
D Signed field, value that becomes negative the sign bit flips meaning Ex 3, Ex 4
E Zero / degenerate value storing 0, and the all-ones maximum Ex 5
F Packing & sizeof how fields share one storage unit Ex 6
G Zero-width alignment trick forcing a new storage unit Ex 7
H Real-world word problem a hardware status register Ex 8
I Exam twist (address / illegal op) &s.field won't compile Ex 9

Two tiny tools do all the arithmetic below, so let us earn them first.

Figure — Bit fields in structs

The picture above is the mental model for every example: a row of numbered slots, filling left, and a value that "falls off the edge" when it is too wide.


Example 1 — Cell A: choose the smallest width


Example 2 — Cell B: unsigned overflow wraps


Example 3 — Cells C & D: signed field, positive vs negative


Example 4 — Cell D limit: the most-negative value


Example 5 — Cell E: zero and the all-ones maximum


Example 6 — Cell F: packing and sizeof

Figure — Bit fields in structs

Example 7 — Cell G: the zero-width alignment trick

Figure — Bit fields in structs

Example 8 — Cell H: real-world hardware register


Example 9 — Cell I: the exam twist (address is illegal)


Recall Did every cell get covered?

Match each matrix row to its example ::: A→Ex1, B→Ex2, C&D→Ex3+Ex4, E→Ex5, F→Ex6, G→Ex7, H→Ex8, I→Ex9. Every cell hit. ::: Fast recall: what is stored in a 3-bit unsigned field? ::: . Fast recall: signed 5-bit range? ::: .

Connections

  • Bit Fields in Structs — the parent concept.
  • Structs in C — the container these examples live in.
  • Bitwise operators — manual slicing without bit fields.
  • Data types and sizeof — why a bit is a 2-state switch and units are int-sized.
  • Memory alignment and padding — Example 6 & 7 packing rules.
  • Embedded systems / hardware registers — Example 8's real-world use.
  • Unsigned vs signed integers — the sign-bit logic in Examples 3–4.