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
The right-shift operation may be implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If
number in the expression
number >> x has a signed type and a negative value, the resulting value is implementation-defined.
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.
std::bitset<4> num(std::string("0010")); bool bit_val = num.test(1); // bit_val value is set to true;