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 <class T>
inline unsigned int toIntFromHexString(const T& t) {
unsigned int x;
std::stringstream ss;
ss << std::hex << t;
ss >> 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()>0) {
color.a = toIntFromHexString(stringA);
}
return color;
}
What can be adjusted in the implementation?