如何将二进制转换为十进制

Gol*_*old 22 .net c#

如何转换二进制字符串,例如1001101Decimal?(77)

SLa*_*aks 70

Convert.ToInt32方法具有接受基本参数重载.

Convert.ToInt32("1001101", 2).ToString();
Run Code Online (Sandbox Code Playgroud)


Joh*_*uff 6

看看这个非常相似的问题但是处理十六进制如何在C#中转换十六进制和十进制之间的数字?

Convert.ToInt64(value, 2)
Run Code Online (Sandbox Code Playgroud)


eua*_*nes 5

如果您采用手动方式而不是使用内置 C# 库,则可以使用以下方法:

static int BinaryToDec(string input)
{
    char[] array = input.ToCharArray();
    // Reverse since 16-8-4-2-1 not 1-2-4-8-16. 
    Array.Reverse(array);
    /*
     * [0] = 1
     * [1] = 2
     * [2] = 4
     * etc
     */
    int sum = 0; 

    for(int i = 0; i < array.Length; i++)
    {
        if (array[i] == '1')
        {
            // Method uses raising 2 to the power of the index. 
            if (i == 0)
            {
                sum += 1;
            }
            else
            {
                sum += (int)Math.Pow(2, i);
            }
        }

    }

    return sum;
}
Run Code Online (Sandbox Code Playgroud)

  • 非常真实的安德鲁。我想说,自从我添加此评论以来已经很长时间了,并且绝不建议任何人使用此方法。使用 C# 库。我认为这更多地展示了它如何在逻辑上运作。 (2认同)