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:

Download  Run Code

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.

Download  Run Code

 
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.

Download Code

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.

Download  Run Code

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