简体   繁体   中英

Convert string binary to base 10

I am creating an application that will do the formula shown in this video - The Everything Formula

I suggest you watch it to understand this. I am trying to replicate the part of the video where he takes the graph and gets what 'k', (The y Coordinate), would be. I took every pixel of the image, and put it into a string containing the binary version. The binary number's length is so large, I cannot store it as an int or long.

Now, here is the part I cannot solve.

How would I convert a string containing a binary number into a base 10 number also in string format?

I Cannot use a long or int type, they are not large enough. Any conversion using the int type will also not work.

Example code:

    public void GraphUpdate()
    {
        string binaryVersion = string.Empty;

        for (int i = 0; i < 106; i++)
        {
            for (int m = 0; m < 17; m++)
            {
                PixelState p = Map[i, m]; // Map is a 2D array of PixelState, representing the grid / graph.

                if (p == PixelState.Filled)
                {
                    binaryVersion += "1";
                }
                else
                {
                    binaryVersion += "0";
                }
            }
        }

        // Convert binaryVersion to base 10 without using int or long
    }

public enum PixelState
{
    Zero,
    Filled
}

You can use BigInteger class, which is part of .NET 4.0. See MSDN BigInteger Constructor , which takes as input byte[]. This byte[] is your binary number.
Result string can be retrieved by calling BigInteger.ToString()

Try using Int64. That works up to 9,223,372,036,854,775,807:

using System;

namespace StackOverflow_LargeBinStrToDeciStr
{
    class Program
    {
        static void Main(string[] args)
        {
            Int64 n = Int64.MaxValue;
            Console.WriteLine($"n = {n}"); // 9223372036854775807

            string binStr = Convert.ToString(n, 2);
            Console.WriteLine($"n as binary string = {binStr}"); // 111111111111111111111111111111111111111111111111111111111111111

            Int64 x = Convert.ToInt64(binStr, 2);
            Console.WriteLine($"x = {x}"); // 9223372036854775807

            Console.ReadKey();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM