[英]how to print hex value of an enum to a string in c++
如何将以下enum
的十六进制值转换为字符串并将其存储在变量中。
enum {
a = 0x54,
b,
c
};
例如
auto value = a;
std::string value_as_hex = to_hex(a);
我如何写to_hex
如果要打印枚举的十六进制值,则可以将printf与%x
占位符一起使用。 例如
#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);
}
该程序的输出是
54
a6
ff
以下解决方案如何?
std::ostringstream str;
str << std::hex << a;
auto x = str.str();
您可以编写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";
}
输出:
0x1234
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.