🎉 Before you dive into this article...
🚀 Check out our vibrant new community at CoderLegion.com!
💡 Share your knowledge, connect with like-minded developers, and grow together.
👉 Click here to join now!
Problem:
How to convert int to hex string c++.
I need someones' help to solve this.
Thanks
Solution:
Use 's std::hex. If you print, just send it to std::cout, if not, then use std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first << with << "0x" or whatever you like if you wish.
Other manips of interest are std::oct (octal) and std::dec (back to decimal).
One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
So finally, I'd suggest such a function:
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
I hope this will solve your issue
Thanks
Top comments (0)