Convert Hex Color To RGB

Description: Takes a supplied 3 or 6 character hex color value and returns a pointer to a 3 integer array representing the red, green, blue colors values (RGB). Assumes a proper hex value is supplied. Requires <string> and <sstream> as well as standard namespace to be used.
Tested Platform: Visual Studio 2010, 32-bit, Windows 7
Language: C/C++
// Takes a 3 character or 6 character hex color value
// and returns a pointer to an array of three RGB values.
// Assumes valid hex value.

int * hex2rgb(string hex) {
	int* rgb = new int[3];
	stringstream ss;
	string str;

	// Drop a hash if the value has one
	if (hex[0] == '#') {
		hex.erase(0,1);
	}

	int size = hex.size();

	for (int i = 0; i < 3; i++) {
		// Determine 3 or 6 character format.
		if (size == 3) { str = string(2, hex[i]); }
		else if (size == 6) { str = hex.substr(i * 2, 2); }
		else { break; }

		ss << std::hex << str;
		ss >> rgb[i];
		ss.clear();
	}

	return rgb;
}

Submitted: February 11, 2014

Return to the snippets listing