Convert a hexadecimal string to an integer in C++
This post will discuss how to convert a hexadecimal string to an integer in C++.
1. Using String Stream
When the basefield format flag is set to hex for the string stream, the integer values inserted into the stream are expressed in radix 16. This can be easily done with the std::hex manipulator, as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "3e8"; unsigned int i; std::istringstream iss(s); iss >> std::hex >> i; std::cout << i << std::endl; // 1000 return 0; } |
2. Using std::stoul
Another option is to use the std::stoul function for converting a hexadecimal string to an unsigned integer in the specified base. The stoul function was introduced in C++11 and is defined in the header <string> and uses std::strtoul to perform the conversion. Also see std::stoi, std::stol, and std::stoull.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <sstream> int main() { std::string s = "3e8"; unsigned int i = std::stoul(s, nullptr, 16); std::cout << i << std::endl; // 1000 return 0; } |
The std::stoul function throws std::invalid_argument exception on a bad input and std::out_of_range on integer overflow. Note that std::stoul converts the strings like 3e8x to integer 1000 (hex 3e8) and doesn’t throw any exception.
3. Using boost::lexical_cast
If you’re already using boost C++ library, you can convert a hexadecimal string to an integer with boost::lexical_cast<int>, as shown below. Note that the boost::lexical_cast uses string streams behind the scenes.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <boost/lexical_cast.hpp> int main() { std::string s = "3e8"; try { unsigned int i = boost::lexical_cast<int>(s); std::cout << i << std::endl; // 1000 } catch(boost::bad_lexical_cast &e) { // bad input - handle exception } return 0; } |
4. Using sscanf
Finally, we can use the sscanf() function to convert a hexadecimal C-string to an integer using the format string %x. You can do something like below to make it work with std::string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> int main() { std::string s = "3e8"; int i; sscanf(s.c_str(), "%x", &i); std::cout << i << std::endl; // 1000 return 0; } |
That’s all about converting a hexadecimal string to an integer 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 :)