Chu*_*Chu -3 c++ string binary decimal radix
如何将C++字符串(仅包含“0”或“1”)直接根据其字面值转换为二进制数据?
例如,我有一个字符串str,它的值是0010010。现在我想将此字符串转换为二进制形式变量,或等于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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试stoi过stod,但它们都不起作用。他们都将二进制0b0010010视为十进制10010。那么我怎样才能达到这个要求呢?多谢!
std::stoi有一个可选的第二个参数,用于为您提供有关解析停止位置的信息,以及一个可选的第三个参数,用于传递转换的基数。
int i = stoi(str, nullptr, 2);
Run Code Online (Sandbox Code Playgroud)
这应该有效。
推论:如果有疑问,请检查文档。;-)