How to parse hex strings in C++ using std::stringstream

This function converts any hex string like 55 to its equivalent decimal value:

hex_to_dec.cpp
#include <sstream>
#include <int>

unsigned int hexToDec(const std::string& str) {
    unsigned int ret;
    std::stringstream ss;
    ss << std::hex << str;
    ss >> ret;
    return ret;
}

e.g.

hex_usage_example.cpp
hexToDec("55"); // returns 85

Note that while the code is somewhat concise, it might be neither the most performant nor the most concise option especially for developers that don’t really know std::stringstream.


Check out similar posts by category: C/C++