以C++格式将十六进制字符串转换为十进制数

Convert Hexadecimal string to decimal number in C++

本文关键字:转换 十进制数 字符串 十六进制 C++ 格式      更新时间:2023-10-16

我想在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;
}