private void tbDecimal_TextChanged(object sender, System.EventArgs e) { // Clear string in another textbox if there are non here if (tbDecimal.Text.Length <= 0) tbHex.Text = ""; // Textbox is not empty else { // If another control is simulating the text change, // then do not proceed with the text conversion for this control if (tbDecimal.Focused == false) return; // 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); //txt_bin.Text =String.Format("{0:h2}",uiDecimal); } }
{
// Clear string in another textbox if there are non here
if (tbDecimal.Text.Length <= 0)
tbHex.Text = ""; // Textbox is not empty
else
{
// If another control is simulating the text change,
// then do not proceed with the text conversion for this control
if (tbDecimal.Focused == false)
return; // 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);
//txt_bin.Text =String.Format("{0:h2}",uiDecimal);
}
}
{
/// <summary>
/// NumberUtil :数字和字符串的转换
/// </summary>
public class NumberUtil{ private static readonly String sNumber="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public NumberUtil(){
} /// <summary>
/// 将数字转换成字符串
/// </summary>
/// <param name="n">数字</param>
/// <param name="radix">进制,如:16进制。</param>
/// <returns></returns>
public static String NumToStr(int n,int radix){
if(n < radix){
return sNumber.Substring(n,1);
}
else{
return NumToStr((int)Math.Floor(n/radix),radix) + sNumber.Substring (n % radix, 1);
}
}
/// <summary>
/// 将字符串转换为数字
/// </summary>
/// <param name="s">字符串</param>
/// <param name="radix">进制,如:16进制。</param>
/// <returns></returns>
public static int StrToNum(String s,int radix){
int n = 1;
int nReturn = 0;
s=s.ToUpper();
for(int i = s.Length - 1; i >= 0; i--){
nReturn += sNumber.IndexOf(s.Substring(i, 1)) * n;
n *= radix;
}
return nReturn;
}
}
}