65.9K
CodeProject is changing. Read more.
Home

Hex Converter

Jun 19, 2003

viewsIcon

260907

downloadIcon

3775

This article is about a program which helps you convert numeric value from decimal to hexadecimal representation and vice versa.

Introduction

This article is about how you would go about converting numeric values to hexadecimal and vice versa. The main reason why I did this program is to help me to cheat when playing computer games, mainly role-playing ones cos I normally need to find the correct hex data in those save game file and furthermore I do not have a good hex editor to help me do those conversion. :)

Using the code

The main code used for the conversion are from the System.Convert class. Below is the code that is used to convert a string to unsigned integer while checking for overflow, and then convert it to hexadecimal format before showing it as a string in a text box.

// To hold our converted unsigned integer32 value
uint uiDecimal = 0;

try
{
    // Convert text string to unsigned integer
    uiDecimal = checked((uint)System.Convert.ToUInt32(tbDecimal.Text));
}

catch (System.OverflowException exception) 
{
    // Show overflow message and return
    tbHex.Text = "Overflow";
    return;
}

// Format unsigned integer value to hex and show in another textbox
tbHex.Text = String.Format("{0:x2}", uiDecimal);

and vice versa

// To hold our converted unsigned integer32 value
uint uiHex = 0;

try
{
    // Convert hex string to unsigned integer
    uiHex = System.Convert.ToUInt32(tbHex.Text, 16);
}

catch (System.OverflowException exception) 
{
    // Show overflow message and return
    tbDecimal.Text = "Overflow";
    return;
}

// Format it and show as a string
tbDecimal.Text = uiHex.ToString();

Conclusion

This is my first attempt at C# and WinForms so I believe by starting with such simple and small programs, it will eventually build up my skills and knowledge to attempt bigger ones. :)