std::bit_width

From cppreference.com
< cpp‎ | numeric
Defined in header <bit>
template< class T >
constexpr T bit_width(T x) noexcept;
(since C++20)

If x is not zero, calculates the number of bits needed to store the value x, that is, 1 + floor(log
2
(x))
. If x is zero, returns zero.

This overload only participates in overload resolution if T is an unsigned integer type (that is, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, or an extended unsigned integer type).

Return value

Zero if x is zero; otherwise, one plus the base-2 logarithm of x, with any fractional part discarded.

Notes

This function is equivalent to return std::numeric_limits<T>::digits - std::countl_zero(x);.

Example

#include <bit>
#include <bitset>
#include <iostream>
 
auto main() -> int
{
    for (unsigned x{0}; x != 8; ++x)
    {
        std::cout
            << "bit_width( "
            << std::bitset<4>{x} << " ) = "
            << std::bit_width(x) << '\n';
    }
}

Output:

bit_width( 0000 ) = 0
bit_width( 0001 ) = 1
bit_width( 0010 ) = 2
bit_width( 0011 ) = 2
bit_width( 0100 ) = 3
bit_width( 0101 ) = 3
bit_width( 0110 ) = 3
bit_width( 0111 ) = 3

See also

counts the number of consecutive 0 bits, starting from the most significant bit
(function template)