最終更新日時(UTC):
が更新

履歴 編集

function template
<bit>

std::has_single_bit(C++20)

namespace std {
  template <class T>
  constexpr bool has_single_bit(T x) noexcept;
}

概要

1ビットだけ立っている値をもっているか判定する。

符号なし整数値にこの関数を適用することで、整数値が2の累乗かを判定することができる。

テンプレートパラメータ制約

  • Tが符号なし整数型であること

戻り値

xの値が1ビットだけ立っていればtrue、そうでなければfalseを返す。

例外

投げない

#include <iostream>
#include <bit>

void check_pow2(unsigned int x)
{
  std::cout << x << "\t : " << std::has_single_bit(x) << std::endl;
}

int main()
{
  std::cout << std::boolalpha;

  if (std::has_single_bit(128u)) {
    std::cout << "128 is power of 2" << std::endl;
  }
  check_pow2(0u);
  check_pow2(3u);
  check_pow2(0xffu);

  std::cout << "---" << std::endl;

  check_pow2(1u);
  for (unsigned int i = 2u; i <= 1024u; i *= 2) {
    check_pow2(i);
  }
}

出力

128 is power of 2
0    : false
3    : false
255  : false
---
1    : true
2    : true
4    : true
8    : true
16   : true
32   : true
64   : true
128  : true
256  : true
512  : true
1024     : true

バージョン

言語

  • C++20

処理系

参照