Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::has_single_bit

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

      Checks ifx is an integral power of two.

      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

      true ifx is an integral power of two; otherwisefalse.

      [edit]Notes

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

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

      [edit]Possible implementation

      template<typename T,typename ...U>concept neither=(!std::same_as<T, U>&& ...); template<typename T>concept strict_unsigned_integral=std::unsigned_integral<T>&&    neither<T,bool,char, char8_t,char16_t,char32_t,wchar_t>; // First versionconstexprbool has_single_bit(strict_unsigned_integralauto x)noexcept{return x&&!(x&(x-1));} // Second versionconstexprbool has_single_bit(strict_unsigned_integralauto x)noexcept{returnstd::popcount(x)==1;}

      [edit]Example

      Run this code
      #include <bit>#include <bitset>#include <cmath>#include <iostream> int main(){for(auto u{0u}; u!=0B1010;++u){std::cout<<"u = "<< u<<" = "<<std::bitset<4>(u);if(std::has_single_bit(u))std::cout<<" = 2^"<<std::log2(u)<<" (is power of two)";std::cout<<'\n';}}

      Output:

      u = 0 = 0000u = 1 = 0001 = 2^0 (is power of two)u = 2 = 0010 = 2^1 (is power of two)u = 3 = 0011u = 4 = 0100 = 2^2 (is power of two)u = 5 = 0101u = 6 = 0110u = 7 = 0111u = 8 = 1000 = 2^3 (is power of two)u = 9 = 1001

      [edit]See also

      (C++20)
      counts the number of1 bits in an unsigned integer
      (function template)[edit]
      returns the number of bits set totrue
      (public member function ofstd::bitset<N>)[edit]
      accesses specific bit
      (public member function ofstd::bitset<N>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/numeric/has_single_bit&oldid=182066"

      [8]ページ先頭

      ©2009-2025 Movatter.jp