From cppreference.com
Defined in header
template<classT>constexprintbit_width(Tx)noexcept;(since C++20)Calculates the number of bits needed to store the value x, that is, ⌈log2(x + 1)⌉.
This overload participates in overload resolution only if T is an unsigned integer type (that is, unsignedchar, unsignedshort, unsignedint, unsignedlong, unsignedlonglong, or an extended unsigned integer type).
Parameters
x - unsigned integer value 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 returnstd::numeric_limits<T>::digits-std::countl_zero(x);.
macroValueStdFeature
(C++20)
Integral power-of-2 operations
Example
Run this code
#include<bit>#include<bitset>#include<cstdio>#include<print>intmain(){for(unsignedx{};x!=9;++x){if(std::has_single_bit(x))std::putchar('\n');std::print("bit_width({:04b}) = {}\n",x,std::bit_width(x));}}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 bit_width(1000) = 4 Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++20 the return type of bit_width is the same as the type of its function argument made it intSee also
(C++20)
counts the number of consecutive 0 bits, starting from the most significant bit
(function template)