开发者

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

开发者 https://www.devze.com 2023-03-29 22:52 出处:网络
I have a property that returns System.Numerics.BigInteger. Wh开发者_高级运维en I casting the property to int, I got this error.

I have a property that returns System.Numerics.BigInteger. Wh开发者_高级运维en 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#?


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


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;
}


Having the int.Parse method only works if the initial BigInteger value would fit anyway. If not, try this:

int result = (int)(big & 0xFFFFFFFF);

Ugly? Yes. Works for any BigInteger value? Yes, as it throws away the upper bits of whatever is there.


By trying to improve the @lee-turpin answer when casting negative numbers, I came with a similar solution, but in this case without the issue with negative numbers. In my case, I was trying to have a 32-bit hash value from a BigInteger object.

var h = (int)(bigInteger % int.MaxValue);

Still ugly, but it works with any BigInteger value. Hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消