std::bit_width(3)
std::bit_width(3) π
Okay bestie, this page comes from the C++ Standard Libary manual (that spelling is literally in the header, keep it π), and it's all about std::bit_width. Yes, the name is the same as the thing. Iconic.
πΈ NAME πΈ
std::bit_width β std::bit_width.
β¨ Synopsis β¨
Synopsis says:
Defined in header <bit>
template< class T > (since C++20)
constexpr int bit_width( T x ) noexcept;
If x is not zero, it calculates the number of bits needed to store the value x, that is, \(1 + \lfloor \log_2(x) \rfloor\)1 + floor(log 2(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). Slay, but only for unsigned integers, okay?
π 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 return std::numeric_limits<T>::digits - std::countl_zero(x);.
Feature-test macro tea:
- Feature-test macro:
__cpp_lib_int_pow2β value202002L, Std(C++20), featureIntegral power-of-2 operations.
π₯ Example π₯
// Run this code
#include <bit>
#include <bitset>
#include <iostream>
int main()
{
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
π Defect reports π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
- DR:
LWG 3656β Applied to:C++20; Behavior as published: the return type ofbit_widthis the same as the type of its function argument; Correct behavior: made itint.
π See also π
countl_zero(C++20)β counts the number of consecutive0bits, starting from the most significant bit (function template).
okay bye bestie π β source/version and date: http://cppreference.com, 2024.06.10, and the page is std::bit_width(3). periodt.
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms