Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to check whether the N bit of a number is set in C++

2 Answers

0 votes
#include <iostream>
 
using namespace std;
 
int main()
{
    int number = 173;  // 10101101
    int n = 3, set;
 
    set = (number >> n) & 1;
    cout << set << endl;
     
    n = 4;
    set = (number >> n) & 1;
    cout << set << endl;
 
    return 0;
}
  
  
  
/*
run:
  
1
0
  
*/

 



answered Mar 31, 2019 by avibootz
edited Mar 31, 2019 by avibootz
0 votes
#include <iostream>

using namespace std;

bool n_bit_set(int num, int N) { 
    return num & (1 << (N - 1));
} 

int main() {
    int num = 12; // 1100
    int N = 3;  
    
    if (n_bit_set(num, N)) {
        cout << "Bit set" << endl; 
    }
    else {
        cout << "Bit not set" << endl;  
    }
    
    N = 1;  
    if (n_bit_set(num, N)) {
        cout << "Bit set" << endl;  
    }
    else {
        cout << "Bit not set" << endl;  
    }
}



/*
run:

Bit set
Bit not set

*/

 



answered Aug 23, 2019 by avibootz
...