How to convert a C string (containing only "0" or "1") to binary data directly according to its literal value?
For example, I have a string str
, it's value is 0010010
. Now I want to convert this string to a binary form variable, or a decimal variable equal to 0b0010010
(is 18
).
int main() {
string str_1 = "001";
string str_2 = "0010";
string str = str_1 str_2;
cout << str << endl;
int i = stoi(str);
double d = stod(str);
cout << i << " and " << d << endl;
}
I tried stoi
and stod
, but they all can't work. They all treated binary 0b0010010
as decimal 10010
. So how can I achieve this requirement? Thanks a lot!
CodePudding user response:
std::stoi
has an optional second argument to give you information about where the parsing stopped, and an optional third argument for passing the base of the conversion.
int i = stoi(str, nullptr, 2);
This should work.
Corollary: If in doubt, check the documentation. ;-)
CodePudding user response:
Or there is this fun way of doing it (at least I think it is) at compile time
#include <stdexcept>
#include <string_view>
constexpr auto from_bin(std::string_view&& str)
{
std::size_t value{ 0ul };
for (const char c : str)
{
value <<= 1;
if ((c != '0') && (c != '1')) throw std::invalid_argument("invalid input");
value |= (c == '1');
}
return value;
}
int main()
{
static_assert(5 == from_bin("101"));
static_assert(9 == from_bin("1001"));
static_assert(2 == from_bin("0010"));
return 0;
}