Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Converting Between Hex and Integer

RSS
Modified on Fri, Aug 27, 2010, 1:13 PM by Administrator Categorized as General Information, ┬ĚNet Framework

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);

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.