std::bitset<N>::to_ulong

来自cppreference.com
< cpp‎ | utility‎ | bitset
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
 
unsigned long to_ulong() const
(C++23 起为 constexpr)

转换 bitset 的内容为 unsigned long 整数。

bitset 的首位对应数值的最低有效位,而尾位对应最高有效位。

参数

(无)

返回值

转换出的整数

异常

若值不能以 unsigned long 表示则抛出 std::overflow_error

示例

#include <bitset>
#include <iostream>
#include <stdexcept>
 
int main()
{
    for (unsigned long i = 0; i < 10; ++i)
    {
        std::bitset<5> b(i);
        std::bitset<5> b_inverted = ~b;
        std::cout << i << '\t' << b << '\t' << b_inverted << '\t'
                  << b_inverted.to_ulong() << '\n';
    }
 
    std::cout << std::bitset<32>().to_string('-') << '\n';
 
    try
    {
        std::bitset<128> x(42);
        std::cout << x.to_ulong() << '\n';
        x.flip();
        std::cout << x.to_ulong() << '\n'; // 抛出异常
    }
    catch (const std::overflow_error& ex)
    {
        std::cout << "ex: " << ex.what() << '\n';
    }
}

可能的输出:

0   00000   11111   31
1   00001   11110   30
2   00010   11101   29
3   00011   11100   28
4   00100   11011   27
5   00101   11010   26
6   00110   11001   25
7   00111   11000   24
8   01000   10111   23
9   01001   10110   22
--------------------------------
42
ex: bitset to_ulong overflow error

参阅

返回数据的字符串表示
(公开成员函数)
(C++11)
返回数据的 unsigned long long 整数表示
(公开成员函数)