Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::bit_width

      From cppreference.com
      <cpp‎ |numeric
       
       
      Utilities library
       
       
      Defined in header<bit>
      template<class T>
      constexprint bit_width( T x)noexcept;
      (since C++20)

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

      This overload participates in overload resolution only ifT is an unsigned integer type (that is,unsignedchar,unsignedshort,unsignedint,unsignedlong,unsignedlonglong, or an extended unsigned integer type).

      Contents

      [edit]Parameters

      x - unsigned integer value

      [edit]Return value

      Zero ifx is zero; otherwise, one plus the base-2 logarithm ofx, with any fractional part discarded.

      [edit]Notes

      This function is equivalent toreturnstd::numeric_limits<T>::digits-std::countl_zero(x);.

      Feature-test macroValueStdFeature
      __cpp_lib_int_pow2202002L(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 ) = 0bit_width( 0001 ) = 1bit_width( 0010 ) = 2bit_width( 0011 ) = 2bit_width( 0100 ) = 3bit_width( 0101 ) = 3bit_width( 0110 ) = 3bit_width( 0111 ) = 3

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 3656C++20the return type ofbit_width is the same as the type of its function argumentmade itint

      [edit]See also

      counts the number of consecutive0 bits, starting from the most significant bit
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/numeric/bit_width&oldid=182063"

      [8]ページ先頭

      ©2009-2025 Movatter.jp