1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Write your code here
    unsigned char mask = (1 << pos);

    if (mode == 1) {
        // Set Bit: 使用 Bitwise OR
        return reg | mask;
    } else {
        // Clear Bit: 使用 Bitwise AND 与 NOT
        return reg & ~mask;
    }
    return 0;
}

int main() {
    unsigned char reg;
    int pos, mode;
    scanf("%hhu %d %d", &reg, &pos, &mode);
    printf("%d", modifyBit(reg, pos, mode));
    return 0;
}

Solving Approach

  • unsigned char reg: 使用 8-bit 无符号字符类型,这在嵌入式开发中对应一个 8-bit Hardware Register(范围 0-255)。
  • int pos: 目标位的索引(Index),取值范围为 0 到 7。
  • int mode: 操作模式。1 代表 Set(置位),0代表 Clear(清零)

1. 构造位掩码 (Constructing the Bitmask)

一切操作的基础是生成一个 Bitmask。我们使用左移操作符 $<<$ 将常量 1 移动到目标位置 pos

  • Formula: mask = (1 << pos)
  • 效果: 生成一个只有第 pos 位为 1,其余位均为 0 的字节。例如,若 pos = 3,则 mask0000 1000 (Binary)。

2. 置位操作 (Set Bit Logic)

当需要将某一位强制设为 1 时,使用 Bitwise OR (|)

  • Logic: 根据真值表,$1 \mid X = 1$(无论 $X$ 是 0 还是 1),而 $0 \mid X = X$(保持原值)。
  • Operation: reg | mask
  • 结果: 只有 mask 中为 1 的位(即 pos 位)会被置为 1,寄存器的其他位因与 0 相或而保持不变。

3. 清零操作 (Clear Bit Logic)

当需要将某一位强制设为 0 时,使用 Bitwise AND (&) 结合 Bitwise NOT (~)

  • Step A (Invert Mask): 使用 ~mask 将掩码按位取反。原本只有 pos 位是 1,取反后只有 pos 位是 0,其余全为 1(例如:1111 0111)。
  • Step B (Bitwise AND): 根据真值表,0 \& X = 0,而 1 \& X = X。
  • Operation: reg & (~mask)
  • 结果: 只有 pos 位会因为与 0 相与而被强制归零,其他位因与 1 相与而保持原样。

 

 

Was this helpful?
Upvote
Downvote