std::bit_width
From cppreference.com
 
 
 
 
 
 C++ 
 Feature test macros (C++20)
 Concepts library (C++20)
 Metaprogramming library (C++11)
 Ranges library (C++20)
 Filesystem library (C++17)
 Concurrency support library (C++11)
 Execution control library (C++26)
Utilities library 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
Relational operators (deprecated in C++20) Integer comparison functions  
 
 
 
 Swap and type operations  Common vocabulary types 
 Type support (basic types, RTTI)
 Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
 Coroutine support (C++20)
 Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
  (C++20)(C++20)(C++20)
  (C++20)(C++20)(C++20)
 General utilities
(C++20)(C++20)(C++20)
  (C++20)(C++20)(C++20)
(C++20)
Bit manipulation 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
(C++20)
(C++23)
(C++20)
(C++20)
(C++20)
bit_width
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
Defined in header 
 
 
<bit> 
 template< class T >
constexpr int bit_width( T x ) noexcept;
 
 (since C++20) 
constexpr int bit_width( T x ) noexcept;
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.
This overload participates in overload resolution only 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).
[edit] Parameters
 x
 -
 unsigned integer value
[edit] Return value
Zero if x is zero; otherwise, one plus the base-2 logarithm of x, with any fractional part discarded.
[edit] Notes
This function is equivalent to return std::numeric_limits <T>::digits - std::countl_zero (x);.
| Feature-test macro | Value | Std | Feature | 
|---|---|---|---|
| __cpp_lib_int_pow2 | 202002L | (C++20) | Integral power-of-2 operations | 
[edit] Example
Run this code
#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'; }
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
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior | 
|---|---|---|---|
| LWG 3656 | C++20 | the return type of bit_widthis the same as the type of its function argument | made it int | 
[edit] See also
(C++20)
(function template) [edit]