在 C++ 中将十六进制字符串转换为十进制数

2024-01-09

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

提前致谢。


// 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C++ 中将十六进制字符串转换为十进制数 的相关文章

随机推荐