有人可以给我一个 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();

但是,如果您在没有 LINQ 的情况下查找它,那么

var s = "101011";   //Your Binary String
var dec = 0;
var bl = Regex.Match(s, @"[-01]*");
if(s == bl.Value)
{
    for( int i=0; i<s.Length; i++ ) 
    {
        if( s[s.Length-i-1] == '0' ) 
            continue;
        dec += (int)Math.Pow( 2, i );
    }
}

所以你想检查输入字符串是否是一个有效的二进制数,并且还想把它转换为十进制吗?

以下代码将帮助您:

string inputStr = toBeConverted.Text;
if(inputStr.All(x=> x=='1' || x=='0')) // check all character is either 0 or 1
{
 // it is a valid binary
 string output = Convert.ToInt32(inputStr , 2).ToString(); 
}
else
{
    // Display message that not a valid binary
}

最新更新