This post will discuss how to convert an integer to hex string in C++.

1. Using std::ostringstream

A simple solution to convert an integer to a hex string in C++ is using the std::hex manipulator with std::ostringstream. This would require <sstream> header. The following program demonstrates it:

Download  Run Code

 
To prepend the hex string with radix specifier 0x, do like:

Download  Run Code

 
We can further pad the hex string with leading zeros of desired length using the std::setfill and std::setw function from <iomanip> header.

Download  Run Code

2. Using std::format

Since C++20, the recommended option is to use the formatting library for converting an integer to a hex string. It contains the std::format function in <format> header, which can be used as follows:

Download Code

 
The std::format is based on the {fmt} library. Before C++20, we can use the {fmt} library to achieve the same.

Download Code

 
If the boost library is available, try using the format class boost::format, which is defined in <boost/format.hpp>. It offers printf-like formatting, as shown below:

Download Code

That’s all about converting an integer to hex string in C++.