Hexadecimal To RGB

This algorithm converts hexadecimal color code to RGB color model.



									/*****Please include following header files*****/
// string
/***********************************************/

/*****Please use following namespaces*****/
// std
/*****************************************/

class RGB
{
public:
	unsigned char R;
	unsigned char G;
	unsigned char B;

	RGB(unsigned char r, unsigned char g, unsigned char b)
	{
		R = r;
		G = g;
		B = b;
	}
	bool Equals(RGB rgb)
	{
		return (R == rgb.R) && (G == rgb.G) && (B == rgb.B);
	}
};

static int HexadecimalToDecimal(string hex) {
	int hexLength = hex.length();
	double dec = 0;

	for (int i = 0; i < hexLength; ++i)
	{
		char b = hex[i];

		if (b >= 48 && b <= 57)
			b -= 48;
		else if (b >= 65 && b <= 70)
			b -= 55;

		dec += b * pow(16, ((hexLength - i) - 1));
	}

	return (int)dec;
}

static RGB HexadecimalToRGB(string hex) {
	if (hex[0] == '#')
		hex = hex.erase(0, 1);

	unsigned char r = (unsigned char)HexadecimalToDecimal(hex.substr(0, 2));
	unsigned char g = (unsigned char)HexadecimalToDecimal(hex.substr(2, 2));
	unsigned char b = (unsigned char)HexadecimalToDecimal(hex.substr(4, 2));

	return RGB(r, g, b);
}
								


Example

									string data = "#520057";
RGB value = HexadecimalToRGB(data);
								


Output

									R: 82
G: 0
B: 87