C++ 如何将十六进制整数转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12851379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ How do I convert Hex Integer to String?
提问by tony gil
Possible Duplicate:
How to convert a number to string and vice versa in C++
可能的重复:
如何在 C++ 中将数字转换为字符串,反之亦然
In C++ how do you convert a hexadecimal integer into a string representation of the decimal value of the original hex?
在 C++ 中,如何将十六进制整数转换为原始十六进制十进制值的字符串表示形式?
Let us say we have an integer whose hexadecimal representation is a1a56
(which in decimal equals 662102
) and you want to convert this to a string "662102"
假设我们有一个整数,其十六进制表示为a1a56
(十进制等于662102
),并且您想将其转换为字符串“662102”
How would you solve this?
你会如何解决这个问题?
ps: i suggest a functional solution as an answer, feel free to shoot it down (in a polite manner, if possible)
ps:我建议使用功能性解决方案作为答案,请随意将其击落(如果可能,请以礼貌的方式)
回答by GWW
You can use stringstreams:
您可以使用字符串流:
int x = 0xa1a56;
std::stringstream ss;
ss << x;
cout << ss.str();
Or if you prefer a function:
或者,如果您更喜欢函数:
std::string convert_int(int n)
{
std::stringstream ss;
ss << n;
return ss.str();
}
Edit: Make sure you #include <sstream>
编辑:确保你 #include <sstream>
回答by dasblinkenlight
You can read the number from a string stream as hex, and write it back to a different string stream as decimal:
您可以从字符串流中以十六进制形式读取数字,并将其以十进制形式写回到不同的字符串流中:
int x;
istringstream iss("a1a56");
iss >> hex >> x;
ostringstream oss;
oss << x;
string s(oss.str());
回答by jogojapan
The simplest way of doing this, using the latest version of the C++ Standard (C++11), is to use the std::to_string
function:
使用最新版本的 C++ 标准 (C++11) 执行此操作的最简单方法是使用以下std::to_string
函数:
#include <iostream>
#include <string>
int main()
{
/* Convert: */
std::string s { std::to_string(0xa1a56) };
/* Print to confirm correctness: */
std::cout << s << std::endl;
return 0;
}
回答by tony gil
std::string HexDec2String(int hexIn) {
char hexString[4*sizeof(int)+1];
// returns decimal value of hex
sprintf(hexString,"%i", hexIn);
return std::string(hexString);
}