65.9K
CodeProject 正在变化。 阅读更多。
Home

十六进制转换器

2003年6月19日

viewsIcon

261392

downloadIcon

3775

本文介绍了一个程序,它可以帮助你将十进制数值转换为十六进制表示,反之亦然。

引言

本文介绍的是如何将数值转换为十六进制以及反之。我编写这个程序的主要原因是帮助我在玩电脑游戏时作弊,主要是角色扮演游戏,因为我通常需要在那些存档文件中找到正确的数据,而且我也没有一个好的十六进制编辑器来帮助我进行这些转换。:)

使用代码

用于转换的主要代码来自 System.Convert 类。以下是用于将字符串转换为无符号整数,同时检查溢出,然后将其转换为十六进制格式,最后将其显示为文本框中的字符串的代码。

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

以及反之

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

结论

这是我第一次尝试 C# 和 WinForms,所以我相信从这样简单的小程序开始,最终会积累我的技能和知识,以便尝试更大的程序。:)

© . All rights reserved.