【问题标题】:Convert string binary to base 10将字符串二进制转换为基数 10
【发布时间】:2017-04-05 04:22:47
【问题描述】:

我正在创建一个应用程序,它将执行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
}

【问题讨论】:

  • “我建议你看它来理解这一点”--- :-D
  • "如何将包含二进制数的字符串转换为同样以字符串格式的以 10 为底的数字?"如果您给我们一个您想要转换的字符串的示例,而不是强迫我们编译和调试示例代码,那就更好了。
  • 在其核心,String 只是 Bytes 的数组 - 你可以将你正在做的任何事情重新加工成一个数组吗?

标签: c# numeric


【解决方案1】:

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

【讨论】:

  • 二进制字符串到字节[]的转换可以找到here
【解决方案2】:

尝试使用 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多