C# Programming > Drawing

C# Hex to RGB Converter

c# hex to rgb


C#.NET does not automatically work with HTML colors, colors in hex representation. To work with HTML colors in .NET, we can write a function to convert hex to RGB colors in C#.

Before converting web colors to .NET RGB colors, we need to know the format of hex colors.

Hex Color Format

Hex colors are generally written in two ways, both of which begin with the symbol "#". The first way uses 6 characters, each two characters represent the values of red, green, and blue in that order. However the values are written using hexadecimal numbers. So for example, the hex color #0012FF would mean the red value is 0, the green value is 18 (12 in hexadecimal), and 255 (FF in hexadecimal).

The second way to write hex colors is to use only 3 characters. This is simply a short version of the 6 characters format, eliminated repeated characters. So for example, #36F is the same as #3366FF.

With this information, we can write a C# function to parse the hex string and convert it into a regular RGB color.

Converting to RGB

The only thing you need to convert hex to RGB is a way to convert those hexadecimal values, such as "FF", into decimal values (255 in this case). The .NET Framework provides programmers with an easy way to do so:

int.Parse("FF", System.Globalization.NumberStyles.AllowHexSpecifier);

The NumberStyles parameter is important, otherwise the function will either fail or give you the wrong value. The rest is simple string parsing to convert hex color to RGB.

Back to C# Article List