我想寫一個程序,測試如果字符串是一個有效的二進制文件,並將其轉換爲十進制?下面是我的代碼不能正常工作有人可以給我一個在c#中的示例程序算法嗎?
private void BinarytoDecimal_Click(object sender, EventArgs e)
{
string a = "";
a = toBeConverted.Text;
long y;
y = Convert.ToInt64(a);
for (int x = 0; x < a.Length; x++)
{
char h = a[x];
if (h > '1' && h < '0')
{
MessageBox.Show("it is not a valid binary");
break;
}
if(x == a.Length - 1)
{
long d = 0 , i = 0 , r , n;
n = Convert.ToInt64(a);
while (n != 0) {
r = n % 10;
n /= 10;
d += r * Math.Pow(2, i);
++i;
}
labelConverted.Text = d.ToString() + " base10";
}
}
}
爲什麼不'Convert.ToInt32( 「YourBinaryString」,2)的ToString();' –
見https://msdn.microsoft.com/en-us /library/1k20k614.aspx有關使用基地轉換的詳細信息。 – paxdiablo