Checking a bit

suggest change

C-style bit-manipulation

The value of the bit can be obtained by shifting the number to the right x times and then performing bitwise AND (&) on it:

(number >> x) & 1LL;  // 1 if the 'x'th bit of 'number' is set, 0 otherwise

Before C++20, if number has a signed type and a negative value, number >> x is implementation-defined: the shift may be arithmetic or logical. C++20 requires an arithmetic right shift. 1LL << x is undefined if x is negative or not less than the width of long long, and in C++11 it is also undefined when the shift moves a 1 into the sign bit.

If we need the value of that bit directly in-place, we could instead left shift the mask:

(number & (1LL << x));  // (1 << x) if the 'x'th bit of 'number' is set, 0 otherwise

Either can be used as a conditional, since all non-zero values are considered true.

Using std::bitset

std::bitset<4> num(std::string("0010"));
bool bit_val = num.test(1);  // bit_val value is set to true;

Feedback about page:

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



Table Of Contents