Hexadecimal To RGB

This algorithm converts hexadecimal color code to RGB color model.



									/*****Please include following header files*****/
// math.h
/***********************************************/

struct RGB
{
	unsigned char R;
	unsigned char G;
	unsigned char B;
};

char* AppendString(const char* str1, const char* str2) {
	int str1Len = strlen(str1);
	int str2Len = strlen(str2);
	int strLen = str1Len + str2Len + 1;
	char* str = malloc(strLen);

	for (int i = 0; i < str1Len; i++)
		str[i] = str1[i];

	for (int i = 0; i < str2Len; i++)
		str[(str1Len + i)] = str2[i];

	str[strLen - 1] = '\0';

	return str;
}

char* GetSubString(char* str, int index, int count) {
	int strLen = strlen(str);

	if (count < 0) count = strLen;

	int lastIndex = index + count;

	if (index >= 0 && lastIndex > strLen) return "";

	char* subStr = malloc(count + 1);

	for (int i = 0; i < count; i++) {
		subStr[i] = str[index + i];
	}

	subStr[count] = '\0';

	return subStr;
}

char* RemoveString(char* str, int index, int count) {
	int strLen = strlen(str);
	int lastIndex = index + count;

	char* s = GetSubString(str, 0, index);
	s = AppendString(s, GetSubString(str, lastIndex, strLen - lastIndex));

	return s;
}

char* HexadecimalToDecimal(char* hex) {
	int hexLength = strlen(hex);
	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;
}

struct RGB HexadecimalToRGB(char* hex) {
	if (hex[0] == '#')
		hex = RemoveString(hex, 0, 1);

	struct RGB rgb;

	rgb.R = (unsigned char)HexadecimalToDecimal(GetSubString(hex, 0, 2));
	rgb.G = (unsigned char)HexadecimalToDecimal(GetSubString(hex, 2, 2));
	rgb.B = (unsigned char)HexadecimalToDecimal(GetSubString(hex, 4, 2));

	return rgb;
}
								


Example

									char* data = "#520057";
struct RGB value = HexadecimalToRGB(data);
								


Output

									R: 82
G: 0
B: 87