std::bit_width
來自 cppreference.com
定義於標頭檔案 <bit> |
||
template< class T > constexpr int bit_width( T x ) noexcept; |
(C++20 起) | |
若 x 非零,則計算儲存值 x 所需的位數,即 1 + floor(log2(x))。若 x 為零,則返回零。
僅當 T
為無符號整型(即 unsigned char、unsigned short、unsigned int、unsigned long、unsigned long long 或擴充套件無符號整型)時,此過載才參與過載決議。
目錄 |
[編輯] 引數
x | - | 無符號整型值 |
[編輯] 返回值
若 x 為零則返回零;否則返回 x 的以 2 為底的對數加一,捨棄任何小數部分。
[編輯] 註記
此函式等價於 return std::numeric_limits<T>::digits - std::countl_zero(x);。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_int_pow2 |
202002L |
(C++20) | 整數次冪操作 |
[編輯] 示例
執行此程式碼
#include <bit> #include <bitset> #include <iostream> int main() { for (unsigned x{}; x != 010; ++x) std::cout << "bit_width( " << std::bitset<4>{x} << " ) = " << std::bit_width(x) << '\n'; }
輸出
bit_width( 0000 ) = 0 bit_width( 0001 ) = 1 bit_width( 0010 ) = 2 bit_width( 0011 ) = 2 bit_width( 0100 ) = 3 bit_width( 0101 ) = 3 bit_width( 0110 ) = 3 bit_width( 0111 ) = 3
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3656 | C++20 | bit_width 的返回型別與其函式引數型別相同 |
改為 int |
[編輯] 參閱
(C++20) |
計算從最高有效位開始的連續 0 位的數量 (函式模板) |