如何将任意长的二进制字符串转换为十进制?

问题描述 投票:0回答:1

我正在寻找一种将任意较长的二进制字符串转换为其等效十进制的算法。我见过的解决方案使用库函数来执行转换,但是如果二进制字符串超过处理器可以容纳的最大数量,则此方法将无效。

例如,字符串“ 1”后跟300个“ 0”将使您2升至301次幂。 300位超出了大多数处理器可容纳在其寄存器存储器中的范围。

是否有一种简单的算法可以一次生成一个字符,而不必为每个数字计算2的中间幂?

谢谢!

binary type-conversion decimal data-conversion
1个回答
0
投票
using System;

public class Program
{
    public static void Main()
    {       
        string testCase = "0001001000000010000000000010000111000011000101100000001100000000000010010100110100100011001001000101010010001100011100110000110010000001011000100101010001100001001000010100100100000000100001010000011100000001111111111111110101000000000111110111000100000110";

        uint[] G = new uint[(testCase.Length / 32) + 1]; 
        uint g = 0;

        for (int i = 0; i < testCase.Length; i++)
        {
            G[(i / 32)] += (uint)((testCase[testCase.Length - (i +1)] & 1) << (i % 32));
        }

        for (int i = 0; i < testCase.Length; i++)
        {
            g += (G[(i / 32)] << (31 - (i % 32))) >> 31;
        }

        Console.WriteLine(g);
        for (int i = 0; i < (testCase.Length / 32) + 1; i++)
        {
            Console.WriteLine(G[i]);
        }       
        Console.ReadLine();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.