Convert hex color string to SDL Color I am writing a small game and as a part of it I load json config with colors definitions in a format of strings #00ff00.

Then I am using this function to convert these strings to SDL Color structure. I am assuming that all color strings are a valid hex colors (between 6-7 chars, depending if # (hash) is provided at the beginning).

template &lt;class T&gt;
inline unsigned int toIntFromHexString(const T&amp; t) {

    unsigned int x;
    std::stringstream ss;
    ss &lt;&lt; std::hex &lt;&lt; t;
    ss &gt;&gt; x;
    return x;

}


inline SDL_Color stringToSDLColor(std::string colorString) {

    SDL_Color color;

    if (colorString[0]=='#') {
        colorString.erase(0,1);
    }

    std::string stringR = colorString.substr(0,2);
    std::string stringG = colorString.substr(2,2);
    std::string stringB = colorString.substr(4,2);
    std::string stringA = colorString.substr(6,2);

    color.r = toIntFromHexString(stringR);
    color.g = toIntFromHexString(stringG);
    color.b = toIntFromHexString(stringB);
    if (stringA.length()&gt;0) {
        color.a = toIntFromHexString(stringA);
    }

    return color;

}


What can be adjusted in the implementation?
Rather than breaking the string into substrings, then converting each individually from a hex string to an integer, I'd probably convert the entire string at once, then use bit shifting to get the pieces you care about.

SDL_Color hex2sdl(std::string input) {

    if (input[0] == '#')
        input.erase(0, 1);

    unsigned long value = stoul(input, nullptr, 16);

    SDL_Color color;

    color.a = (value &gt;&gt; 24) &amp; 0xff;
    color.r = (value &gt;&gt; 16) &amp; 0xff;
    color.g = (value &gt;&gt; 8) &amp; 0xff;
    color.b = (value &gt;&gt; 0) &amp; 0xff;
    return color;
}


This simplifies the code quite a bit, and at least in my mind makes it rather easier to read.

Another point to consider (when/if your compiler supports it) would be to use an std::string_view instead of a std::string for the input. A string_view is something like a pointer/length, so (when needed) it can trim the # from the beginning without copying all the data like an actual string normally will. Even if your compiler supports string_view itself, however, it may easily not support passing a string_view to std::stoul, which kind of ruins the idea (for now).