我在网上搜索了一下,但好像没有解决我的问题的方法。基本上,我有一个包含十六进制内存地址(例如0x10FD7F04)的
我需要将此字符串转换为int值,但保留十六进制表示法,即0x。有什么办法可以做到这一点吗?
std::string
。这个数字是从文本文件中读取并保存为std::string
的。我需要将此字符串转换为int值,但保留十六进制表示法,即0x。有什么办法可以做到这一点吗?
#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
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;
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::string hexstring("0x10FD7F04");
int num;
sscanf( hexstring.data(), "%x", &num);