BigInteger.intValue() 在 C# 中等效

BigInteger.intValue() equivalent in C#

我正在尝试将 java 代码转换为 C#,但在处理 BigInteger 操作时遇到了问题。我找到了一些关于 C# 中的 BigInteger 实现和 intValue 本身的资源。但是没有关于 C# 中 BigInteger.intValue 等价物的线索。 Java中的定义是:

Converts this BigInteger to an int. Thisconversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification:if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned.Note that this conversion can lose information about theoverall magnitude of the BigInteger value as well as return a result with the opposite sign.

但是在 C# 中使用 (int) 得到类似的结果会导致错误:

Value was either too large or too small for an Int32.

我也试过只使用低字节没有成功 如果有人帮助,我们将不胜感激

要获得 Java 的行为,屏蔽掉值的低位并转换结果:

int result = (int) (uint) (bi & uint.MaxValue);

(这是使用implicit UInt32 to BigInteger conversion, and the explicit conversion for the other way round