Extract and Insert a Register Field
Hardware registers pack several fields into one word. Write:
field_get(reg, shift, width): returns thewidth-bit field starting at bitshift.field_set(reg, shift, width, val): returnsregwith that field replaced byval, leaving every other bit unchanged. Bits ofvalthat do not fit in the field must be ignored.
Both must work for width == 32.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Build the mask without ever computing 1u << 32. 0xFFFFFFFFu >> (32 - width) gives width ones, as long as width is at least 1.
#include <stdio.h>
#include <stdint.h>
static inline uint32_t ones(unsigned width)
{
return width ? (0xFFFFFFFFu >> (32u - width)) : 0u;
}
uint32_t field_get(uint32_t reg, unsigned shift, unsigned width)
{
return (reg >> shift) & ones(width);
}
uint32_t field_set(uint32_t reg, unsigned shift, unsigned width, uint32_t val)
{
uint32_t mask = ones(width) << shift;
return (reg & ~mask) | ((val << shift) & mask);
}
The textbook (1u << width) - 1 breaks for width == 32 because shifting by the full type width is undefined. Shifting the all-ones value right avoids that.
When applied to a real register this is a read-modify-write. If an ISR or another core can modify the same register, protect it with a critical section, or use hardware set/clear registers. In the Linux kernel, the same job is done by FIELD_GET() and FIELD_PREP() with GENMASK().
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(field_get(0x0000AB00u, 8, 8) == 0xABu);
CHECK(field_get(0xF0000000u, 28, 4) == 0xFu);
CHECK(field_get(0x12345678u, 0, 32) == 0x12345678u);
CHECK(field_set(0xFFFFFFFFu, 4, 4, 0x0u) == 0xFFFFFF0Fu);
CHECK(field_set(0x00000000u, 4, 4, 0x1Fu) == 0x000000F0u); /* extra bits dropped */
CHECK(field_set(0xDEADBEEFu, 0, 32, 0x1u) == 0x1u);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}