在C#中将int转换为/从System.Numerics.BigInteger转换

时间:2011-08-19 21:21:36

标签: c# casting biginteger

我有一个返回System.Numerics.BigInteger的属性。当我将属性转换为int时,我收到此错误。

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

如何在C#中将int转换为System.Numerics.BigInteger?/

5 个答案:

答案 0 :(得分:9)

conversion from BigInteger to Int32是明确的,因此仅将BigInteger变量/属性分配给int变量不起作用:

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?)"

这样可行(尽管如果值太大而无法放入int变量,它可能会在运行时抛出异常):

BigInteger big = ...

int result = (int)big;      // works

请注意,如果BigInteger中的object值已装箱,则无法将其取消装箱并同时将其转换为int

BigInteger original = ...;

object obj = original;      // box value

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

这有效:

BigInteger original = ...;

object obj = original;            // box value

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

int result = (int)big;            // works

答案 1 :(得分:1)

以下是将BigInteger转换为int

的一些选择
BigInteger bi = someBigInteger;
int i = (int)bi;
int y = Int32.Parse(bi.ToString()); 

注意但是如果BigInteger值太大,它会抛出一个新的异常,所以可能会这样做

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

或者

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

或者

int t = 0;
if (bi > int.MaxValue || bi < int.MinValue)
{
    Console.WriteLine("Oh Noes are ahead");
}
else
{
    t = (int)bi;
}

答案 2 :(得分:1)

只有初始BigInteger值适合时才能使用int.Parse方法。如果没有,试试这个:

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

丑?是。 适用于任何BigInteger值?是的,因为它抛弃了那里的任何东西。

答案 3 :(得分:0)

答案 4 :(得分:0)

通过在输出负数时尝试改进@ lee-turpin答案,我得到了类似的解决方案,但在这种情况下没有负数的问题。就我而言,我试图从BigInteger对象获得32位哈希值。

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

仍然很难看,但它适用于任何BigInteger值。希望它有所帮助。

相关问题