Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I append data to a std::string in hex format?

Tags:

I have an existing std::string and an int. I'd like to concatenate the ASCII (string literal) hexadecimal representation of the integer to the std::string.

For example:

 std::string msg = "Your Id Number is: ";
 unsigned int num = 0xdeadc0de; //3735929054

Desired string:

std::string output = "Your Id Number is: 0xdeadc0de";

Normally, I'd just use printf, but I can't do this with a std::string (can I?)

Any suggestions as to how to do this?

like image 914
samoz Avatar asked Aug 10 '09 14:08

samoz


1 Answers

Use a stringstream. You can use it as any other output stream, so you can equally insert std::hex into it. Then extract it's stringstream::str() function.

std::stringstream ss;
ss << "your id is " << std::hex << 0x0daffa0;
const std::string s = ss.str();
like image 163
xtofl Avatar answered Sep 22 '22 18:09

xtofl