[英]how to print hex value of an enum to a string in c++
How do I convert the hex value of the below enum
to a string and store it in a variable. 如何将以下
enum
的十六进制值转换为字符串并将其存储在变量中。
enum {
a = 0x54,
b,
c
};
For example 例如
auto value = a;
std::string value_as_hex = to_hex(a);
How do I write to_hex
我如何写
to_hex
If you want to print the hex value of an enum you can use printf with the %x
placeholder. 如果要打印枚举的十六进制值,则可以将printf与
%x
占位符一起使用。 For example 例如
#include <cstdio>
enum Foo {
a = 0x54,
b = 0xA6,
c = 0xFF
};
int main() {
Foo e;
e = a;
printf("%x\n",e);
e = b;
printf("%x\n",e);
e = c;
printf("%x\n",e);
}
the output of the program is 该程序的输出是
54
a6
ff
How about the following solution? 以下解决方案如何?
std::ostringstream str;
str << std::hex << a;
auto x = str.str();
You could write your to_hex
function to store the hex representation of the value in a string using stringstreams and IO manipulation : 您可以编写
to_hex
函数,以使用stringstreams和IO操作将值的十六进制表示形式存储在字符串中:
#include <iostream>
#include <sstream>
std::string to_hex(const unsigned a) {
std::stringstream ss;
ss << "0x" << std::hex << a;
return ss.str();
}
int main() {
unsigned value = 0x1234;
std::string value_as_hex = to_hex(value);
std::cout << value_as_hex << "\n";
}
Output: 输出:
0x1234
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.