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

履歴 編集

function template
<bit>

std::bit_width(C++20)

namespace std {
  template <class T>
  constexpr int bit_width(T x) noexcept;
}

概要

値を表現するために必要なビット幅を求める。

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

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

戻り値

x == 0である場合、0を返す。そうでない場合、2を底としてxの対数を求めて、それに1を足した値を返す。その際、小数点以下の値は破棄される。

例外

投げない

#include <iostream>
#include <bit>

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

int main()
{
  std::cout << "129\t : " << std::bit_width(129u) << std::endl;
  convert_to_width(127u);
  convert_to_width(1u);
  convert_to_width(0u);

  std::cout << "---" << std::endl;
  for (unsigned int i = 1024u; i >= 2u; i /= 2) {
    convert_to_width(i);
  }
}

出力

129  : 8
127  : 7
1    : 1
0    : 0
---
1024     : 11
512  : 10
256  : 9
128  : 8
64   : 7
32   : 6
16   : 5
8    : 4
4    : 3
2    : 2

バージョン

言語

  • C++20

処理系

参照