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
...