Project 12: Bitfield Packing Lab

  • File: P12-bitfield-packing-lab.md
  • Main Programming Language: C
  • Alternative Programming Languages: Rust, Go, Python
  • Coolness Level: Level 3 (See REFERENCE.md)
  • Business Potential: Level 2 (See REFERENCE.md)
  • Difficulty: Level 3 (See REFERENCE.md)
  • Knowledge Area: Bitfields
  • Software or Tool: CLI
  • Main Book: “Computer Systems: A Programmer’s Perspective”

What you will build: A simulator that packs multiple sensor values into a single 32-bit word and unpacks them.

Why it teaches binary/hex: Real systems pack fields to save space and bandwidth using masks and shifts.

Core challenges you will face:

  • Field packing -> Bitwise Operations
  • Width validation -> Bits/Bytes/Nibbles
  • Error detection -> Two’s Complement

Real World Outcome

$ bitpack --temp 23 --humidity 55 --status 3
packed: 0x01C837

$ bitunpack 0x01C837
temp: 23
humidity: 55
status: 3

The Core Question You Are Answering

“How do I store multiple values inside one integer without collisions?”

Concepts You Must Understand First

  1. Masks and shifts
    • How do you insert and extract fields?
    • Book Reference: “Computer Systems: A Programmer’s Perspective” - Ch. 2
  2. Range limits
    • How do you enforce field widths?
    • Book Reference: “Computer Systems: A Programmer’s Perspective” - Ch. 2

Questions to Guide Your Design

  1. Field layout
    • How many bits will each field get?
  2. Validation
    • What happens if an input exceeds its allotted width?

Thinking Exercise

Packing Plan

Design a 32-bit layout for three fields: 10 bits, 12 bits, and 4 bits. Draw the bit positions.

Questions to answer:

  • Which bits belong to each field?
  • How do you extract a middle field?

The Interview Questions They Will Ask

  1. “How do you pack multiple fields into one integer?”
  2. “What is the role of masks in bitfield packing?”
  3. “How do you validate field widths?”
  4. “What happens if a field overflows?”
  5. “How would you document a bitfield layout for a team?”

Hints in Layers

Hint 1: Starting Point Create constants for field widths and bit offsets.

Hint 2: Next Level Use (value & mask) « offset to insert.

Hint 3: Technical Details Pseudocode:

packed = (a << offsetA) | (b << offsetB) | c
extractA = (packed >> offsetA) & maskA

Hint 4: Tools/Debugging Print binary output with labeled bit positions for verification.

Books That Will Help

Topic Book Chapter
Bitwise logic “Computer Systems: A Programmer’s Perspective” Ch. 2

Common Pitfalls and Debugging

Problem 1: “Fields overlap”

  • Why: Offsets or widths are miscalculated.
  • Fix: Draw the layout and add assertions for max values.
  • Quick test: Use max values for each field and verify no spillover.

Definition of Done

  • Packs and unpacks fields correctly
  • Rejects values that exceed allocated width
  • Provides a documented bit layout
  • Includes binary visualization output