How do you find the position of the most significant bit (MSB) of an unsigned integer in C++

2 Answers

0 votes
#include <bit>
#include <cstdint>
#include <optional>

/**
 * Returns the zero-based position of the most significant set bit (MSB).
 *
 * Examples:
 *   value = 1   -> 0
 *   value = 2   -> 1
 *   value = 8   -> 3
 *   value = 15  -> 3
 *
 * @param value Unsigned integer to inspect.
 * @return MSB position, or std::nullopt if value is 0.
 */
std::optional<int> msb_position(std::uint32_t value)
{
    if (value == 0U) {
        return std::nullopt;
    }

    constexpr int bit_count = 32;

    return bit_count - 1 - static_cast<int>(std::countl_zero(value));
}


#include <iostream>

int main()
{
    if (const auto pos = msb_position(0x1234U)) { // 0001001000110100
        std::cout << "MSB position = " << *pos << '\n';
    }
    else {
        std::cout << "Value contains no set bits\n";
    }
}


/*
run:

MSB position = 12

*/

 



answered Sep 30 by avibootz
0 votes
#include <cstdint>
#include <optional>

/**
 * Returns the zero-based position of the most significant set bit (MSB).
 *
 * Examples:
 *   value = 1   -> 0
 *   value = 2   -> 1
 *   value = 8   -> 3
 *   value = 15  -> 3
 *
 * @param value Unsigned integer to inspect.
 * @return MSB position, or std::nullopt if value is 0.
 */
std::optional<int> msb_position(std::uint32_t value)
{
    if (value == 0U) {
        return std::nullopt;
    }

    int position = 0;

    while ((value >>= 1U) != 0U) {
        ++position;
    }

    return position;
}


#include <iostream>

int main()
{
    if (const auto pos = msb_position(0x1234U)) { // 0001001000110100
        std::cout << "MSB position = " << *pos << '\n';
    }
    else {
        std::cout << "Value contains no set bits\n";
    }
}


/*
run:

MSB position = 12

*/

 



answered Sep 30 by avibootz
...