How to convert binary to decimal

后端 未结 6 2013
忘掉有多难
忘掉有多难 2020-12-05 07:21

How can I convert a binary string, such as 1001101 to Decimal? (77)

6条回答
  •  隐瞒了意图╮
    2020-12-05 07:51

    If you're after a manual way instead of using built in C# libraries, this would work:

    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;
    }
    

提交回复
热议问题