2017-07-27 154 views
0

号我想一个十六进制字符串转换为十进制数(整数)在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"并将其转换为整数,然后转换为十进制数。

在此先感谢。

+2

那么问题是什么?你有一个工作方式。 – NathanOliver

+0

@NathanOliver我正确更新了它。 – GTAVLover

+1

可能的重复:https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer –

回答

2
// 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; 
} 
+0

谢谢!有效! :-)我搜索了很多次,并没有发现任何东西,因为我搜索的方式。但是,我无法找到[this](https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer)帖子。 – GTAVLover

相关问题