std::bit_width(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

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 β€” value 202002L, Std (C++20), feature Integral 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 of bit_width is the same as the type of its function argument; Correct behavior: made it int.

πŸ‘‘ See also πŸ‘‘

  • countl_zero (C++20) β€” counts the number of consecutive 0 bits, 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