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,870 questions

51,793 answers

573 users

How to check if most significant bit (MSB) of a number is set or not in C++

1 Answer

0 votes
#include <iostream>

using namespace std;

#define BITS sizeof(int) * 8 
 
int main()
{
    int n = 15, msb;
 
    msb = 1 << (BITS - 1);
 
    if (n & msb)
        cout << "MSB set (1)" << endl;
    else
        cout << "MSB not set (0)" << endl;
         
    msb = 1 << (4 - 1);  
    if (n & msb)
        cout << "MSB set (1)" << endl;
    else
        cout << "MSB not set (0)" << endl;
     
    n = -3;   
    msb = 1 << (BITS - 1);  
    if (n & msb)
        cout << "MSB set (1)" << endl;
    else
        cout << "MSB not set (0)" << endl;
 
    return 0;
}
 
 
 
/*
run:
 
MSB not set (0)
MSB set (1)
MSB set (1)
 
*/

 



answered Mar 31, 2019 by avibootz
...