Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::bit_ceil

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

      Calculates the smallest integral power of two that is not smaller thanx.

      If that value is not representable inT, the behavior is undefined. Call to this function is permitted inconstant evaluation only if the undefined behavior does not occur.

      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 - value of unsigned integer type

      [edit]Return value

      The smallest integral power of two that is not smaller thanx.

      [edit]Exceptions

      Throws nothing.

      [edit]Notes

      Prior toP1956R1, the proposed name for this function template wasceil2.

      Feature-test macroValueStdFeature
      __cpp_lib_int_pow2202002L(C++20)Integral power-of-2 operations

      [edit]Possible implementation

      See possible implementations inlibstdc++ (gcc) andlibc++ (clang).

      template<typename T,typename ...U>concept neither=(!std::same_as<T, U>&& ...); template<std::unsigned_integral T>    requires neither<T,bool,char, char8_t,char16_t,char32_t,wchar_t>constexpr T bit_ceil(T x)noexcept{if(x<= 1u)return T(1);ifconstexpr(std::same_as<T, decltype(+x)>)return T(1)<<std::bit_width(T(x-1));else{// for types subject to integral promotionconstexprint offset_for_ub=std::numeric_limits<unsigned>::digits-std::numeric_limits<T>::digits;return T(1u<<(std::bit_width(T(x-1))+ offset_for_ub)>> offset_for_ub);}}

      [edit]Example

      Run this code
      #include <bit>#include <bitset>#include <iostream> int main(){using bin=std::bitset<8>;for(auto x{0U};0XA!= x;++x)std::cout<<"bit_ceil( "<< bin(x)<<" ) = "<< bin(std::bit_ceil(x))<<'\n';}

      Output:

      bit_ceil( 00000000 ) = 00000001bit_ceil( 00000001 ) = 00000001bit_ceil( 00000010 ) = 00000010bit_ceil( 00000011 ) = 00000100bit_ceil( 00000100 ) = 00000100bit_ceil( 00000101 ) = 00001000bit_ceil( 00000110 ) = 00001000bit_ceil( 00000111 ) = 00001000bit_ceil( 00001000 ) = 00001000bit_ceil( 00001001 ) = 00010000

      [edit]See also

      (C++20)
      finds the largest integral power of2 not greater than the given value
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/numeric/bit_ceil&oldid=182065"

      [8]ページ先頭

      ©2009-2025 Movatter.jp