While you can use the division and remainder method, C++ provides std::bitset and the string conversion std::stoul, std::stoull that can automate the conversion for you.
The following example loops prompting the user for input of a binary value and converts the value to unsigned long
so long as the binary digits entered are 64 or less. Simply press Enter without entering a value to end the program:
#include <iostream>
#include <string>
#include <bitset>
int main() {
for (;;) { /* loop continually */
std::string input{}; /* binary input from user */
unsigned long value = 0; /* value to hold conversion to ulong */
/* prompt for input, read/validate input */
std::cout << "\nenter a binary value: ";
if (!getline(std::cin, input) || input.size() == 0) {
break;
}
if (input.size() > 64) { /* validate 64 binary digits or less */
std::cerr << "error: input exceeds 64-bit conversion limit.\n";
continue;
}
value = std::bitset<64>(input).to_ulong(); /* convert to ulong */
std::cout << input << ": " << value << '\n'; /* output result */
}
}
Note: you would also want to validate the user has entered only '0'
s and '1'
s which you can do simply with std::basic_string::find_first_not_of, e.g.
if (input.find_first_not_of("01") != std::string::npos) {
std::cerr << "error: invalid input not '0' and '1'\n";
continue;
}
(simply add the if
statement before the conversion and assignment to value
)
Example Use/Output
./bin/bitset_to_ulong
enter a binary value: 1010
1010: 10
enter a binary value: 10000000
10000000: 128
enter a binary value: 1111
1111: 15
enter a binary value: 1234
error: invalid input not '0' and '1'
enter a binary value:
Just an alternative way of doing the same that C++ has provided a convenient way to do in C++11 and forward.