Converting Between Hex and Integer

Hex to Integer

The following C# code demonstrates how to convert a hexadecimal color value to its three decimal components. The key to the conversion is the Convert.ToInt32(s, 16) function call. (The second parameter is the base to convert from.)

{copytext|Hex2Int}
private void ConvertToRgb()
{
    try
    {
        string hex = "000000" + uxHexTextBox.Text ;
        hex = hex.Substring(hex.Length - 6, 6);
        string result = "RGB(";

        for (int i = 0; i <= 4; i += 2)
        {
            string s = hex.Substring(i, 2);
            result += Convert.ToInt32(s, 16).ToString();
            if (i < 4)
                result += ", ";
        }
        result += ")";
        uxRgbTextBox.Text = result;
        Clipboard.SetText(result);
        uxHexTextBox.SelectAll();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, Application.ProductName);
    }
}

Integer to Hex

The following code demonstrates how to convert from and INT to a hex string.

{copytext|Int2Hex}
int i = 32;
string s = String.Format("{0:X}", i);