GTA*_*ver 2 c++ string hex decimal
我想在 C++ 中将十六进制字符串转换为十进制数(整数)并尝试使用以下方法:
std::wstringstream SS;
SS << std::dec << stol(L"0xBAD") << endl;
Run Code Online (Sandbox Code Playgroud)
但它0反而返回了2989。
std::wstringstream SS;
SS << std::dec << reinterpret_cast<LONG>(L"0xBAD") << endl;
Run Code Online (Sandbox Code Playgroud)
但它-425771592反而返回了2989。
但是,当我像下面这样使用它时,它可以正常工作2989并按预期提供。
std::wstringstream SS;
SS << std::dec << 0xBAD << endl;
Run Code Online (Sandbox Code Playgroud)
但我想输入一个字符串并2989作为输出,而不是像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;
}
Run Code Online (Sandbox Code Playgroud)