Skip to content

Instantly share code, notes, and snippets.

@ixqbar
Created October 14, 2015 02:34
Show Gist options
  • Save ixqbar/3b1d2713105d7567ac2e to your computer and use it in GitHub Desktop.
Save ixqbar/3b1d2713105d7567ac2e to your computer and use it in GitHub Desktop.
color string to rgb
#include <iostream>
#include <sstream>
int main()
{
// The hex code that should be converted ...
std::string hexCode;
std::cout << "Please enter the hex code: ";
std::cin >> hexCode;
// ... and the target rgb integer values.
int r, g, b;
// Remove the hashtag ...
if(hexCode.at(0) == '#') {
hexCode = hexCode.erase(0, 1);
}
// ... and extract the rgb values.
std::istringstream(hexCode.substr(0,2)) >> std::hex >> r;
std::istringstream(hexCode.substr(2,2)) >> std::hex >> g;
std::istringstream(hexCode.substr(4,2)) >> std::hex >> b;
// Finally dump the result.
std::cout << std::dec << "Parsing #" << hexCode
<< " as hex gives (" << r << ", " << g << ", " << b << ")" << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment