Convert an integer to hex string in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <sstream> int main() { int i = 1000; std::ostringstream ss; ss << std::hex << i; std::string result = ss.str(); std::cout << result << std::endl; // 3e8 return 0; } |
To prepend the hex string with radix specifier 0x, do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <sstream> int main() { int i = 1000; std::ostringstream ss; ss << "0x" << std::hex << i; std::string result = ss.str(); std::cout << result << std::endl; // 0x3e8 return 0; } |
We can further pad the hex string with leading zeros of desired length using the std::setfill and std::setw function from <iomanip> header.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <sstream> #include <iomanip> int main() { int i = 1000; std::ostringstream ss; ss << "0x" << std::setfill('0') << std::setw(8) << std::hex << i; std::string result = ss.str(); std::cout << result << std::endl; // 0x000003e8 return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <format> int main() { int i = 1000; std::cout << std::format("{:#x}", i) << std::endl; // 0x3e8 std::cout << std::format("{:#08x}", i) << std::endl; // 0x000003e8 return 0; } |
The std::format is based on the {fmt} library. Before C++20, we can use the {fmt} library to achieve the same.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <fmt/format.h> int main() { int i = 1000; std::cout << fmt::format("{:#x}", i) << std::endl; // 0x000003e8 std::cout << fmt::format("{:#08x}", i) << std::endl; // 0x000003e8 return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <boost/format.hpp> int main() { int i = 1000; std::cout << (boost::format("%x") % i).str(); // 3e8 return 0; } |
That’s all about converting an integer to hex string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)