GTAVLover GTAVLover - 1 year ago 99
C++ Question

Convert Hexadecimal string to decimal number in C++

I want to convert a hexadecimal string to a decimal number (integer) in C++ and tried with following ways:

std::wstringstream SS;
SS << std::dec << stol(L"0xBAD") << endl;


But it returned
0
instead
2989
.

std::wstringstream SS;
SS << std::dec << reinterpret_cast<LONG>(L"0xBAD") << endl;


But it returned
-425771592
instead
2989
.

But, when I use it like below, it works fine and gives
2989
as expect.

std::wstringstream SS;
SS << std::dec << 0xBAD << endl;


But I want to input a string and get
2989
as output, instead integer input like
0xBAD
. For example, I want to input
"0xBAD"
and cast it to integer and then convert to a decimal number.

Thanks in advance.

Answer Source
// 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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download