Changing the nth bit to x

suggest change

C-style bit-manipulation

// Bit n is set if x is 1 and cleared if x is 0.
// x must be 0 or 1. -x is all-bits-one only in two's complement, which C++20 requires.
// 1LL << n is undefined if n is negative or not less than the width of long long,
// and before C++20 it is also undefined if the shift changes the sign bit.
number ^= (-x ^ number) & (1LL << n);

Using std::bitset

set(n,val) - sets bit n to the value val.

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents