Skip to content

BigInteger.intValue() equivalent in C#

I am trying to translate a java code into C# and encountered a problem working with BigInteger operations. I found several resources on BigInteger implementation in C# and the intValue itself. But no clue on BigInteger.intValue equivalent in C#. The definition in Java is:

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.

But getting similar results using (int) in C# results in error:

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

I also tried to use only the low bytes with no success It would be appreciated if someone helps

Answer

To get Java’s behaviour, mask out the lower bits of the value and convert the result:

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

(This is using the implicit UInt32 to BigInteger conversion, and the explicit conversion for the other way round)