Search code examples
c++bitset

C++: How to get the MSB (Most-Significant Bit) of a Bitset (using bitwise operators)?


I am trying to convert a decimal number to a bitset of length 27 and then retrieve the MSB (left-most bit) from that bitset using bitwise operators. For example, the number 67108865 is expressed as 100000000000000000000000001 and the MSB is 1. Another example is the number 1 which is expressed as 000000000000000000000000001 and the MSB is 0.

Below is my C++ code:

unsigned int value = 67108865;
bitset<27> bs(value);
int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;
cout << most_significant_bit << endl;

However, I receive the following error:

error: no match for ‘operator&’ (operand types are ‘std::bitset<27>’ and ‘int’) int most_significant_bit = bs >> (sizeof(value)*8 - 1) & 1;

How would I retrieve the MSB using bitwise operators?


Solution

  • Just use the operator[] to get the most significant bit.

    bitset<27> bs(value);
    int ms_bit = bs[bs.size()-1];