Find most significant set bit of a number in C++



Here we will see if a number is given, then how to find the value of Most Significant Bit value, that is set. The value is power of 2. So if the number is 10, MSB value will be 8.

We have to find the position of MSB, then find the value of the number with a set-bit at kth position.

Example

#include<iostream>
#include<cmath>
using namespace std;
int msbBitValue(int n) {
   int k = (int)(log2(n));
   return (int)(pow(2, k));
}
int main() {
   int n = 150;
   cout << "MSB bit value is: "<< msbBitValue(n);
}

Output

MSB bit value is: 128

Advertisements