RGB To Hexadecimal
This algorithm converts RGB color model to hexadecimal color code.
public struct RGB
{
private byte _r;
private byte _g;
private byte _b;
public RGB(byte r, byte g, byte b)
{
this._r = r;
this._g = g;
this._b = b;
}
public byte R
{
get { return this._r; }
set { this._r = value; }
}
public byte G
{
get { return this._g; }
set { this._g = value; }
}
public byte B
{
get { return this._b; }
set { this._b = value; }
}
public bool Equals(RGB rgb)
{
return (this.R == rgb.R) && (this.G == rgb.G) && (this.B == rgb.B);
}
}
public static string RGBToHexadecimal(RGB rgb)
{
string rs = DecimalToHexadecimal(rgb.R);
string gs = DecimalToHexadecimal(rgb.G);
string bs = DecimalToHexadecimal(rgb.B);
return '#' + rs + gs + bs;
}
private static string DecimalToHexadecimal(int dec)
{
if (dec <= 0)
return "00";
int hex = dec;
string hexStr = string.Empty;
while (dec > 0)
{
hex = dec % 16;
if (hex < 10)
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 48).ToString());
else
hexStr = hexStr.Insert(0, Convert.ToChar(hex + 55).ToString());
dec /= 16;
}
return hexStr;
}
Example
RGB data = new RGB(82, 0, 87);
string value = RGBToHexadecimal(data);
Output
#520057