Appearance
C 用掩码读取和改写寄存器位域
给定一个 32 位字,把 bit[6:4] 改成 5,原字的其他位保留。示例使用内存变量,可以先在电脑上运行。
沿执行路径读代码
field_mask()检查起始位置与字段宽度。宽为 3 时得到低位掩码0x07,完整 32 位宽时直接使用UINT32_MAX。change_field()判断新值能否放进字段,再把掩码和值左移到起始位置。先清除原字段,随后合并新值。read_field()右移并掩码。字段超出 32 位或新值过宽时,函数返回false,输出参数保持原值。
在硬件中先确认寄存器允许读改写,并确保这次读写不会与中断或其他执行上下文争用。写 1 清除的挂起位采用直接写对应掩码的方式,例如 EXTI 共享中断。
完整源码
c
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
static uint32_t field_mask(unsigned shift, unsigned width)
{
// 1. 位编号从 0 起。先判断 shift,再计算剩余位数,避免无符号下溢。
if (shift >= 32U || width == 0U || width > 32U - shift) { return 0U; }
// 2. 32 位字段没有同宽的移位操作,直接返回全 1。
return width == 32U ? UINT32_MAX : (UINT32_C(1) << width) - 1U;
}
// 成功时把字段右对齐到 out。参数无效时返回 false,保持 out 原值。
static bool read_field(uint32_t word, unsigned shift, unsigned width, uint32_t *out)
{
const uint32_t mask = field_mask(shift, width);
if (out == NULL || mask == 0U) { return false; }
*out = (word >> shift) & mask;
return true;
}
// 成功时给出新字,其他位保留。新值放不下时拒绝写入,out 保持原值。
static bool change_field(uint32_t word, unsigned shift, unsigned width,
uint32_t value, uint32_t *out)
{
// 1. 先验证字段范围与数值。只要有一位落到 mask 外就拒绝。
const uint32_t mask = field_mask(shift, width);
if (out == NULL || mask == 0U || (value & ~mask) != 0U) { return false; }
// 2. 将掩码和新值左移到字段位置。先清旧字段,再合并新值。
*out = (word & ~(mask << shift)) | (value << shift);
return true;
}
int main(void)
{
// 1. 在内存里的示例字修改 bit[6:4],再读出字段核对。
const uint32_t initial = UINT32_C(0xA5A500F3);
uint32_t word = initial;
uint32_t field = 0U;
assert(change_field(word, 4U, 3U, 5U, &word));
assert(read_field(word, 4U, 3U, &field) && field == 5U);
assert(word == UINT32_C(0xA5A500D3));
printf("0x%08" PRIX32 " -> 0x%08" PRIX32 ", field=%" PRIu32 "\n",
initial, word, field);
// 2. 越界与过宽值都保留旧值。最后核对整字字段和最高单个位。
assert(!change_field(word, 4U, 3U, 8U, &word));
assert(!change_field(word, 31U, 2U, 0U, &word));
assert(!change_field(word, 0U, 0U, 0U, &word));
assert(!read_field(word, 32U, 1U, &field) && field == 5U);
assert(word == UINT32_C(0xA5A500D3));
assert(change_field(word, 0U, 32U, UINT32_MAX, &word) && word == UINT32_MAX);
assert(change_field(word, 31U, 1U, 0U, &word) && word == UINT32_C(0x7FFFFFFF));
puts("bit field: bounds, full width and unrelated bits preserved");
}编译和观察
在仓库根目录使用 C11 编译器。PowerShell 命令如下。
powershell
New-Item -ItemType Directory -Force .work | Out-Null
gcc -std=c11 -Wall -Wextra -Werror -pedantic examples/c/bit-field/main.c -o .work/bit-field.exe
& ./.work/bit-field.exe应看到 0xA5A500F3 -> 0xA5A500D3, field=5。自检还核对过宽输入、超出最高位、全宽和第 31 位。
练习
预测题 向三位字段写入 8,函数会得到什么结果?
核对预测
三位最大值是 7,8 & ~0x07 非零。change_field() 返回 false,原字保留。
改动题 把 bit[6:4] 的新值改成 2,重新跑自测。
核对改法
原低字节 0xF3 先清掩码 0x70,得到 0x83,再合并 0x20。更新读回断言及两处完整字比较,结果应为 0xA5A500A3。
验证记录
Windows GCC 和隔离主机环境均通过编译、自测。含越界位移和完整 32 位边界。