`

二进制,八进制,十六进制数转换为十进制数的算法

阅读更多

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ExToD
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


//参数Num为需要转换的数,n为该数的进制
public string ToD(string Num, int n)
{
char[] nums=Num.ToCharArray ();
int d = 0;
for (int i = 0; i <nums.Length ; i++)
{
string number=nums [i].ToString ();
if (n == 16)
{
switch (number.ToUpper ())
{
case "A":
number = "10";
break;
case "B":
number = "11";
break;
case "C":
number = "12";
break;
case "D":
number = "13";
break;
case "E":
number = "14";
break;
case "F":
number = "15";
break;
}

}
Double power = Math.Pow(Convert.ToDouble (n),Convert.ToDouble ( nums.Length - (i + 1)));
d = d + Convert.ToInt32 (number) * Convert.ToInt32 (power);
}
return d.ToString ();
}

private void btnBtoD_Click(object sender, EventArgs e)
{
this.txtBtoD.Text = ToD(this.txtB.Text, 2);//将二进制转换为十进制
}
private void btnOtoD_Click(object sender, EventArgs e)
{
this.txtOtoD.Text = ToD(this.txtO.Text, 8);//将八进制转换为十进制
}

private void btnXtoD_Click(object sender, EventArgs e)
{
this.txtXtoD.Text = ToD(this.txtX.Text, 16);//将十六进制转换为十进制
}

//只允许输入0、1和退格键
private void txtB_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 48&&e.KeyChar!=49&&e.KeyChar!=8)
{
e.Handled = true;
}
}
//只允许输入0~8和退格键
private void txtO_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(e.KeyChar >= 48 && e.KeyChar <= 55) && e.KeyChar != 8)
{
e.Handled = true;
}
}
//只允许输入0~9、a~f和退格键
private void txtX_KeyPress(object sender, KeyPressEventArgs e)
{

if (!(e.KeyChar >= 48 && e.KeyChar <= 57) && !(e.KeyChar >= 97 && e.KeyChar <= 102) && e.KeyChar != 8)
{
e.Handled = true;
}
}


}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics