将第 n 位更改为 x

C 风格的位操作

// Bit n will be set if x is 1 and cleared if x is 0.
number ^= (-x ^ number) & (1LL << n);

使用 std::bitset

set(n,val) - 将 n 设置为值 val。

std::bitset<5> num(std::string("00100"));
num.set(0,true);  // num is now 00101
num.set(2,false); // num is now 00001