C++中十六进制字符串转十进制数

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"并将其转换为整数,然后转换为十进制数。

提前致谢。

Llu*_*art 6

// 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)

  • 虽然这段代码可以解决问题,但如果解释一下它是如何/为什么这样做的,答案会更好。请记住,您的答案不仅适用于提出问题的用户,也适用于找到该问题的所有其他人。 (2认同)