How to convert binary to decimal

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

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

6条回答
  •  青春惊慌失措
    2020-12-05 07:56


    I have tried this after reading your problem. It is a bit longer but it provides a solution. I saved binary elements in an array to get a solution. Like I said It is a bit longer, much shorter ways can be found.

            // Binary ------> Decimal 
            int len;
            double deci = 0;
    
            Console.Write("Length of binary number: ");
            len = Convert.ToInt32(Console.ReadLine());
    
            int[] bnry = new int[len];
    
            for (int i = 0; i < len; i++)
            {
                Console.Write("{0} index of binary number: ", i);
                bnry[i] = Convert.ToInt32(Console.ReadLine());
            }
            Console.Write("Your binary number: ");
            for (int i = len - 1; 0 <= i; i--)
            {
    
                Console.Write(bnry[i]);
    
            }
    
            Console.Write("\nDecimal number: ");
            for (int i = 0; i < len; i++)
            {
                deci += (bnry[i] * Math.Pow(2, i));
            }
            Console.Write(deci);
    

提交回复
热议问题