将std::string类型的数字转换为十六进制数

3
我在网上搜索了一下,但好像没有解决我的问题的方法。基本上,我有一个包含十六进制内存地址(例如0x10FD7F04)的std::string。这个数字是从文本文件中读取并保存为std::string的。
我需要将此字符串转换为int值,但保留十六进制表示法,即0x。有什么办法可以做到这一点吗?
3个回答

5
你可以使用C++11的std::stoi函数来实现:

std::stoi


#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string your_string_rep{"0x10FD7F04"};
    int int_rep = stoi(your_string_rep, 0, 16);
    std::cout << int_rep << '\n';
    std::cout << std::hex << std::showbase << int_rep << '\n';
}

输出:

285048580
0x10fd7f04

4
我需要将这个字符串转换为int值,但要保留十六进制表示法0x。有没有任何方法可以实现这一点?
你的问题有两个部分:
  1. Convert the string hexadecimal representation to an integer.

    std::string your_string_rep{ "0x10FD7F04" };
    std::istringstream buffer{ your_string_rep };
    int value = 0;
    buffer >> std::hex >> value;
    
  2. Keeping the hex notation on the resulting value. This is not necessary/possible, because an int is already a hexadecimal value (and a decimal value and a binary value, depending on how you interpret it).

换句话说,使用上述代码,您只需编写以下内容:
    assert(value == 0x10FD7F04); // will evaluate to true (assertion passes)

为什么不使用std::stoul函数? - Veritas

1
另外,您可以使用类似于以下内容的东西。
std::string hexstring("0x10FD7F04");
int num;
sscanf( hexstring.data(), "%x", &num);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接