Kamrul
Kamrul

Reputation: 13

How to check a particular bit of a "long long int" in C++

I'm trying to check a particular bit of a long long integer

long long int val=23355665641326;
int bit_no=32;
if( (val & (1<<bit_no)) == 0)
  cout<<bit_no<<"'th bit is not set\n";
else
  cout<<bit_no<<"'th bit is set\n";

the binary equivalent of 23355665641326 is -

101010011110111101010001001110110111101101110
            ^

we see, 32'th bit is set. But my code returns not set :(
how can i check the bit?

Upvotes: 1

Views: 571

Answers (3)

Ali Akber
Ali Akber

Reputation: 3800

You can use 1LL<<bit_no to check the bit status of a long long int.

As you are dealing with long long int you need to use long long type 1
Because if you use normal 1(int), you can check upto 31 bit
So just change the checking portion like this -

if( (val & (1LL<<bit_no) ) == 0)
            ^^^

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

Your life would be easy if you use std::bitset instead:

constexpr auto N = CHAR_BIT * sizeof(long long int);

std::bitset<N> val(23355665641326LL);

Now you can test a particular bit as:

if ( val.test(i) ) {
      //bit at index i is set!
}

Or you can use the faster — but unsafe — version, as:

if ( val[i] ) {
      //bit at index i is set!
}

test() performs bound check and throws std::out_of_range if the index is invalid, whereas operator[] does not, in which case invalid index leads to undefined behavior.

Upvotes: 6

NaCl
NaCl

Reputation: 2723

To overcome with the need of adding the suffix to the check simply do something like this:

if(!!((val >> bit_no) & 1))
    std::cout << "not set";
else
    std::cout << "is set";

Upvotes: 1

Related Questions