[英]Convert Hexadecimal string to decimal number in C++
我想在C ++中将十六进制字符串转换为十进制数字(整数),并尝试使用以下方法:
std::wstringstream SS;
SS << std::dec << stol(L"0xBAD") << endl;
但它返回0
而不是2989
。
std::wstringstream SS;
SS << std::dec << reinterpret_cast<LONG>(L"0xBAD") << endl;
但是它返回-425771592
而不是2989
。
但是,当我像下面那样使用它时,它可以正常工作并给出2989
的期望值。
std::wstringstream SS;
SS << std::dec << 0xBAD << endl;
但是我想输入一个字符串并获得2989
作为输出,而不是像0xBAD
这样的整数输入。 例如,我要输入"0xBAD"
并将其"0xBAD"
转换为整数,然后转换为十进制数。
提前致谢。
// stol example
#include <iostream> // std::cout
#include <string> // std::string, std::stol
int main ()
{
std::string str_dec = "1987520";
std::string str_hex = "2f04e009";
std::string str_bin = "-11101001100100111010";
std::string str_auto = "0x7fffff";
std::string::size_type sz; // alias of size_t
long li_dec = std::stol (str_dec,&sz);
long li_hex = std::stol (str_hex,nullptr,16);
long li_bin = std::stol (str_bin,nullptr,2);
long li_auto = std::stol (str_auto,nullptr,0);
std::cout << str_dec << ": " << li_dec << '\n';
std::cout << str_hex << ": " << li_hex << '\n';
std::cout << str_bin << ": " << li_bin << '\n';
std::cout << str_auto << ": " << li_auto << '\n';
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.