将字符串二进制转换为基数10

时间:2017-04-05 04:22:48

标签: c# numeric

我正在创建一个应用程序,它将执行this video - The Everything Formula

中显示的公式

我建议你观看它以理解这一点。我正在尝试复制视频的一部分,在那里他获取图表并获得' k'(y坐标)。我拍摄了图像的每个像素,并将其放入包含二进制版本的字符串中。二进制数的长度是如此之大,我无法将其存储为int或long。

现在,这是我无法解决的部分。

如何将包含二进制数的字符串转换为字符串格式的基数为10的数字?

不能使用long或int类型,它们不够大。使用int类型的任何转换也不起作用。

示例代码:

    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
}

2 个答案:

答案 0 :(得分:1)

您可以使用BigInteger类,它是.NET 4.0的一部分。 请参见MSDN BigInteger Constructor,其作为输入字节[]。 这个字节[]是你的二进制数 可以通过调用BigInteger.ToString()

来检索结果字符串

答案 1 :(得分:0)

尝试使用Int64。这最多可达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();
        }
    }
}
相关问题