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

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.

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:


Bit manipulation:
* Checking a bit

Table Of Contents
6 Bit manipulation
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype