#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", ®, &pos, &mode);
printf("%d", modifyBit(reg, pos, mode));
return 0;
}一切操作的基础是生成一个 Bitmask。我们使用左移操作符 $<<$ 将常量 1 移动到目标位置 pos。
mask = (1 << pos)pos 位为 1,其余位均为 0 的字节。例如,若 pos = 3,则 mask 为 0000 1000 (Binary)。当需要将某一位强制设为 1 时,使用 Bitwise OR (|)。
reg | maskmask 中为 1 的位(即 pos 位)会被置为 1,寄存器的其他位因与 0 相或而保持不变。当需要将某一位强制设为 0 时,使用 Bitwise AND (&) 结合 Bitwise NOT (~)。
~mask 将掩码按位取反。原本只有 pos 位是 1,取反后只有 pos 位是 0,其余全为 1(例如:1111 0111)。reg & (~mask)pos 位会因为与 0 相与而被强制归零,其他位因与 1 相与而保持原样。