Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting int to/from System.Numerics.BigInteger in C#

I have a property that returns System.Numerics.BigInteger. When I casting the property to int, I got this error.

Cannot convert type 'System.Numerics.BigInteger' to 'int'

How can I convert int to/from System.Numerics.BigInteger in C#?

like image 583
prosseek Avatar asked Aug 19 '11 21:08

prosseek


People also ask

How to convert string to BigInteger in c#?

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.

How do you convert BigInt to INT?

BigInteger. intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int.

Is INT64 same as BigInt?

BigInt is not the same as INT64 no matter how much they look alike. Part of the reason is that SQL will frequently convert Int/BigInt to Numeric as part of the normal processing. So when it goes to OLE or . NET the required conversion is NUMERIC to INT.


2 Answers

The conversion from BigInteger to Int32 is explicit, so just assigning a BigInteger variable/property to an int variable doesn't work:

BigInteger big = ...

int result = big;           // compiler error:
                            //   "Cannot implicitly convert type
                            //    'System.Numerics.BigInteger' to 'int'.
                            //    An explicit conversion exists (are you
                            //    missing a cast?)"

This works (although it might throw an exception at runtime if the value is too large to fit in the int variable):

BigInteger big = ...

int result = (int)big;      // works

Note that, if the BigInteger value is boxed in an object, you cannot unbox it and convert it to int at the same time:

BigInteger original = ...;

object obj = original;      // box value

int result = (int)obj;      // runtime error
                            //   "Specified cast is not valid."

This works:

BigInteger original = ...;

object obj = original;            // box value

BigInteger big = (BigInteger)obj; // unbox value

int result = (int)big;            // works
like image 189
dtb Avatar answered Oct 04 '22 02:10

dtb


Here are some choices that will convert BigInteger to int

BigInteger bi = someBigInteger;
int i = (int)bi;
int y = Int32.Parse(bi.ToString()); 

Watch Out though if the BigInteger value is too large it will throw a new exception so maybe do

int x;
bool result = int.TryParse(bi.ToString(), out x);

Or

try
{
    int z = (int)bi;
}
catch (OverflowException ex)
{
    Console.WriteLine(ex);
}

Or

int t = 0;
if (bi > int.MaxValue || bi < int.MinValue)
{
    Console.WriteLine("Oh Noes are ahead");
}
else
{
    t = (int)bi;
}
like image 32
Trio Avatar answered Oct 04 '22 00:10

Trio