2017-07-27 210 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

相關問題