3

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.

GTAVLover
  • 1,407
  • 3
  • 22
  • 41

1 Answers1

7
// 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;
}
from56
  • 3,976
  • 2
  • 13
  • 23
  • Thank You! It worked! :-) I googled many times about this and found nothing, because of the way I searched. But, I was unable to find [this](https://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer) post. – GTAVLover Jul 27 '17 at 14:20
  • 2
    While this code may solve the problem the answer would be a lot better with an explanation on how/why it does. Remember that your answer is not just for the user that asked the question but also for all the other people that find it. – NathanOliver Oct 01 '18 at 12:40