How do I convert the hex value of the below enum
to a string and store it in a variable.
enum {
a = 0x54,
b,
c
};
For example
auto value = a;
std::string value_as_hex = to_hex(a);
How do I write to_hex
How do I convert the hex value of the below enum
to a string and store it in a variable.
enum {
a = 0x54,
b,
c
};
For example
auto value = a;
std::string value_as_hex = to_hex(a);
How do I write to_hex
If you want to print the hex value of an enum you can use printf with the %x
placeholder. 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 :
#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