C systems practice
Defensive 32-bit C systems toolkit
A compact C17 library for bit and field operations, backed by boundary, failure-path, state-transition, and bit-pattern checks.
Contract path
Designed for failure paths too
- 01Contract
- 02Input validation
- 03Defined bit operation
- 04Unchanged-on-failure output
- 05Test matrix
6Bit and field helpers
2Population-count methods
61Recorded checks
0Strict-warning diagnostics
API behavior
What the toolkit proves
- Implemented set, clear, toggle, test, extract, and insert helpers with explicit bounds and null-output handling.
- Implemented fixed-iteration and Kernighan population counts for comparison.
- Kept output values unchanged when validation fails and verified boundary behavior around bit 31 and full-width fields.
- Compiled under C17 with strict warnings and ran 61 recorded checks.
Reasoning model
Defined operations first
- 1
Use exact-width unsigned types and fixed-width integer constants to avoid signed-shift and width surprises.
- 2
Validate the full field range before building a mask, including the special 32-bit-width case.
- 3
Test success, rejection, boundary, and state-preservation behavior—not only expected arithmetic results.
Selected source
Boundary-safe operations
bool bits32_insert_field(uint32_t value,
uint32_t lsb,
uint32_t width,
uint32_t field,
uint32_t *result)
{
uint32_t mask;
uint32_t destination_mask;
if (width < UINT32_C(1) || width > UINT32_C(32) ||
lsb >= UINT32_C(32) || width > (UINT32_C(32) - lsb) ||
result == NULL) {
return false;
}
mask = (width == UINT32_C(32))
? UINT32_MAX
: (UINT32_C(1) << width) - UINT32_C(1);
if (field > mask) return false;
destination_mask = mask << lsb;
*result = (value & ~destination_mask) | (field << lsb);
return true;
}uint32_t bits32_popcount_fixed(uint32_t value)
{
uint32_t count = UINT32_C(0);
for (uint32_t i = UINT32_C(0); i < UINT32_C(32); ++i) {
count += value & UINT32_C(1);
value >>= 1;
}
return count;
}
uint32_t bits32_popcount_kernighan(uint32_t value)
{
uint32_t count = UINT32_C(0);
while (value != UINT32_C(0)) {
value &= value - UINT32_C(1);
++count;
}
return count;
}