How to find the 3rd bit of a number

I have a question with a problem in c++.
I have to create a program where I have to create one variable from Int and to cout<< on the screen "True" if the 3rd bit is 1.

My question is: How can I see what is the 3rd bit of that number; I’ve tried with bitset, but couldn’t solve it. Please help me.

#include<iostream>
#include<bitset>
using namespace std;
int main()
{
int x; cin >> x;

if (x % 3 != 0 && bitset<32>(1)[2])
{
    cout << "TRUE";
}
else
{
    cout << "FALSE";

}
This should do it right ?

>Solution :

Checking if a given bit is set is a classic pattern that you will encounter in a great many codebase. So even if there are cleaner ways to do it in modern C++, it’s still worth being able to at least recognise the old school pattern when it pops up:

// You will typically see bit masks predefined in constants or an enum.
enum flags {
  FEATURE_1 = 1 << 0,  // first bit
  FEATURE_2 = 1 << 1,  // second bit
  FEATURE_3 = 1 << 2,  // third bit
  FEATURE_4 = 1 << 3,  // fourth bit
};

if(value & FEATURE_3) {
  // the bit is set
}
else {
  //the bit is not set
}

Explanation:

(1 << bit_index): This creates a mask. I.E. a value with only the bit we care about set. E.G. 1 << 3 is 0b00001000 as a 8 bit integer.

val & mask: This does a binary AND between the value and the mask, which will be 0 if and only if the bit is not set. Since any non-zero value is a true, we just use the result of the & as condition.

You could also shift the value and compare against 1, but doing it the other way around has the advantage that the mask can often be precomputed during compilation, so the check becomes a simple binary AND at runtime.

Nowadays, it is neater to do so with std::bitset:

// Replace 4 with the number of meaningful bits
// N.B. index is still 0-based. 1 means the second bit.
if(std::bitset<4>(value).test(2)) {
  // the bit is set
}
else {
  //the bit is not set
}

Leave a Reply