GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::bit_width - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. bit
  3. bit_width

最終更新日時: 2026年09月19日 21時31分51秒 (JST)
rotarymars が更新

履歴 編集

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

処理系

  • Clang: 12.0.1 ✅
  • GCC: 9.1 ✅
  • Visual C++: ??

関連項目

  • stdc_bit_width - C互換のビット操作関数

参照

  • P0556R3 Integral power-of-2 operations
  • P1956R1 On the names of low-level bit manipulation functions
    • std::log2p1からstd::bit_widthに名称変更。変更前の関数名log2p1のp1は、1を足す (plus one) ことを示していた。
  • LWG Issue 3656. Inconsistent bit operations returning a count
    • 戻り値の型をTからintに変更
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.