c#中的system . numeric . biginteger和int之间的转换
本文关键字:int 之间 转换 biginteger 中的 system numeric | 更新日期: 2023-09-27 18:06:14
我有一个返回System.Numerics.BigInteger
的属性。当我将属性转换为int时,我得到了这个错误。
Cannot convert type 'System.Numerics.BigInteger' to 'int'
如何在c#中将int转换为/从System.Numerics.BigInteger
?
从BigInteger到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
以下是将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;
}
拥有int。Parse方法只在初始BigInteger值适合的情况下才有效。如果没有,试试这个:
int result = (int)(big & 0xFFFFFFFF);
丑吗?是的。适用于任何BigInteger值?是的,因为它会丢掉上面的部分
通过尝试改进@lee-turpin的答案,当转换负数时,我提出了一个类似的解决方案,但在这种情况下没有负数的问题。在我的例子中,我试图从一个BigInteger对象获得一个32位的哈希值。
var h = (int)(bigInteger % int.MaxValue);
仍然很难看,但它适用于任何BigInteger值。