#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
*/