Skip to content

Latest commit

 

History

History
88 lines (68 loc) · 1.72 KB

File metadata and controls

88 lines (68 loc) · 1.72 KB

log2p1

  • bit[meta header]
  • std[meta namespace]
  • function template[meta id-type]
  • cpp20[meta cpp]
namespace std {
  template <class T>
  constexpr T log2p1(T x) noexcept;
}

概要

2を底とした整数値の対数を求めて1を足す。

1を足す理由は、対数を求められない0を引数として許容することでnoexceptとし、かつx == 1である場合と区別するためである。関数名log2p1p1は1を足す (plus one) ことを示している。

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

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

戻り値

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

例外

投げない

#include <iostream>
#include <bit>

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

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

  std::cout << "---" << std::endl;
  for (unsigned int i = 1024u; i >= 2u; i /= 2) {
    convert_to_log2(i);
  }
}
  • std::floor2[color ff0000]

出力

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

処理系

参照