1

I'm new to C++ and I have a simple and stupid issue and I hope someone can help me! I have a byte, for example:

uint8_t MyByte = 0x0C;

and I want to convert it into a string corresponding to the hexadecimal MyByte value, in this case "0C". If I try:

std::string MyString = std::to_string(MyByte);

I will obtain: MyString = "12"; I want to obtain MyString = "0C" instead, that is the corresponding hex value. Is it possible?

Thanks!

EDIT: I know there is a similar question on the link provided, but it is not right form me. In fact, if I try:

std::stringstream stream;
stream << std::hex << MyByte;
std::string MyString( stream.str() );

MyString doesn't shows me as expected.

I just tryied this solution, it seems it's working:

std::stringstream stream;
stream << std::hex << (int)MyByte; // cast needed
std::string MyString( stream.str() );
std::transform(strBcc.begin(), strBcc.end(),strBcc.begin(), ::toupper);
ASLaser
  • 11
  • 6

1 Answers1

2

You can use std::ostringstream and std::hex:

std::ostringstream oss;
oss << std::hex << (int)MyByte;

To obtain the string use

std::string MyString = oss.str();
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190