Converting a string into BigInteger

半腔热情 提交于 2020-11-29 04:17:33

问题


I have the following code that creates a very big number (BigInteger) which is converted then into a string.

// It's a console application.
BigInteger bi = 2;
for (int i = 0; i < 1234; i++)
{
   bi *= 2;
}
string myBigIntegerNumber = bi.ToString();
Console.WriteLine(myBigIntegerNumber);

I know that for converting to int we can use Convert.ToInt32 and converting to long we use Convert.ToInt64, but what's about converting to BigInteger?

How can I convert a string (that represents a very very long number) to BigInteger?


回答1:


Use BigInteger.Parse() method.

Converts the string representation of a number in a specified style to its BigInteger equivalent.

BigInteger bi = 2;
for(int i = 0; i < 1234; i++)
{
    bi *= 2;
}

var myBigIntegerNumber = bi.ToString();
Console.WriteLine(BigInteger.Parse(myBigIntegerNumber));

Also you can check BigInteger.TryParse() method with your conversation is successful or not.

Tries to convert the string representation of a number to its BigInteger equivalent, and returns a value that indicates whether the conversion succeeded.




回答2:


Here is another approach which is faster compared to BigInteger.Parse()

public static BigInteger ToBigInteger(string value)
{
    BigInteger result = 0;
    for (int i = 0; i < value.Length; i++)
    {
        result = result * 10 + (value[i] - '0');
    }
    return result;
}


来源:https://stackoverflow.com/questions/14183356/converting-a-string-into-biginteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!