std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
Last Updated :
13 Aug, 2019
Bitset: A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is not there with vector and dynamic array)
std::bitset::to_ullong
This function Converts the contents of the bitset to an unsigned long 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.
Syntax:
bit.to_ullong()
Here bit is a number in bits (i.e., 101 for 5)
Parameters:
- We are not passing any parameters
Return:
- Return the converted integer.
Exceptions:
- overflow_error will occur if the value can not be represented in unsigned long long.
Examples:
Input : 1010
Output : 10
Input : 10000001
Output :129
# CODE 1 :
#include <bitset>
#include <iostream>
#include <limits>
using namespace std;
int main()
{
bitset<numeric_limits<unsigned long long >::digits> b(10);
cout << b << endl << b.to_ullong();
return 0;
}
|
OUTPUT:
0000000000000000000000000000000000000000000000000000000000001010
10
# CODE 2 :
#include <bitset>
#include <iostream>
#include <limits>
using namespace std;
int main()
{
bitset<numeric_limits<unsigned long long >::digits> b(20);
cout << b << endl << b.to_ullong();
return 0;
}
|
OUTPUT:
0000000000000000000000000000000000000000000000000000000000010100
20
std::bitset::to_ulong
This function 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.
Syntax:
bit.to_ulong()
Here bit is a number in bits (i.e., 101 for 5)
Parameters:
We are not passing any parameters
Return:
Return the converted integer.
Exceptions associated:
overflow_error will occur if the value can not be represented in unsigned long.
Examples:
Input : 1010
Output : 10
Input : 10000001
Output :129
# CODE 1 :
#include <bitset>
#include <iostream>
#include <limits>
using namespace std;
int main()
{
bitset<numeric_limits<unsigned long >::digits> b(10);
cout << b << endl << b.to_ulong();
return 0;
}
|
OUTPUT:
0000000000000000000000000000000000000000000000000000000000001010
10
# CODE 2 :
#include <bitset>
#include <iostream>
#include <limits>
using namespace std;
int main()
{
bitset<numeric_limits<unsigned long >::digits> b(20);
cout << b << endl << b.to_ulong();
return 0;
}
|
OUTPUT:
0000000000000000000000000000000000000000000000000000000000010100
20