std::bitset<N>::to_ulong

From cppreference.com
< cpp‎ | utility‎ | bitset
 
 
Utilities library
Language support
Type support (basic types, RTTI)
Library feature-test macros (哋它亢++20)
Dynamic memory management
Program utilities
Coroutine support (哋它亢++20)
Variadic functions
(哋它亢++20)
(哋它亢++26)
(哋它亢++11)
(哋它亢++20)
Debugging support
(哋它亢++26)
(哋它亢++26)
Three-way comparison
(哋它亢++20)(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)
(哋它亢++20)   
(哋它亢++20)(哋它亢++20)(哋它亢++20)
(哋它亢++20)(哋它亢++20)(哋它亢++20)
General utilities
Date and time
Function objects
Formatting library (哋它亢++20)
(哋它亢++11)
Relational operators (deprecated in 哋它亢++20)
Integer comparison functions
(哋它亢++20)(哋它亢++20)(哋它亢++20)   
(哋它亢++20)(哋它亢++20)(哋它亢++20)
(哋它亢++20)
Swap and type operations
(哋它亢++20)
(哋它亢++14)
(哋它亢++11)
(哋它亢++23)
(哋它亢++11)
(哋它亢++23)
(哋它亢++11)
(哋它亢++11)
(哋它亢++17)
Common vocabulary types
(哋它亢++11)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++11)
(哋它亢++11)
(哋它亢++17)
(哋它亢++17)
(哋它亢++23)
Elementary string conversions
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)
(哋它亢++17)


 
 
unsigned long to_ulong() const
(constexpr since 哋它亢++23)

Converts the contents of the bitset to an unsigned long integer.

The first bit of the bitset corresponds to the least significant digit of the number and the last bit corresponds to the most significant digit.

Parameters

(none)

Return value

The converted integer.

Exceptions

Throws std::overflow_error if the value can not be represented in unsigned long.

Example

#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'; // throws
    }
    catch (const std::overflow_error& ex)
    {
        std::cout << "ex: " << ex.what() << '\n';
    }
}

Possible output:

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

See also

returns a string representation of the data
(public member function)
(哋它亢++11)
returns an unsigned long long integer representation of the data
(public member function)