std::bit_width

Header: <bit>

If x is not zero, calculates the number of bits needed to store the value x, that is, (1 + \lfloor \log_2(x) \rfloor)1 + floor(log2(x)). If x is zero, returns zero.

# Declarations

template< class T >
constexpr int bit_width( T x ) noexcept;

(since C++20)

# Parameters

# 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::digits - std::countl_zero(x);.

# Example

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

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 3656C++20the return type of bit_width is the same as the type of its function argumentmade it int

# See also