8

I have a property that returns System.Numerics.BigInteger. When I tried casting the property to an int, I got this error:

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

How can I convert ints to and from System.Numerics.BigInteger in C#?

22
  • 4
    How are you going to deal with values too large to fit into an int? Commented Aug 19, 2011 at 21:23
  • 4
    Can you add some code? BigInteger provides an explicit conversion operator for int, so (int)someBigInteger should work. Commented Aug 19, 2011 at 21:24
  • @Oded : It's pretty temporary code to test this and that. The BigInteger is actually not that big. Commented Aug 19, 2011 at 21:25
  • 1
    I guess it would be rude to "steal" the answer from dtb - maybe you (@dtb) should propse this as an answer... Commented Aug 19, 2011 at 21:25
  • 1
    Why return a BigInteger if it fits in a regular integer to begin with? Commented Aug 19, 2011 at 21:27

4 Answers 4

15

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
Sign up to request clarification or add additional context in comments.

4 Comments

@svick: Which one? I get this: "Cannot implicitly convert type 'System.Numerics.BigInteger' to 'int'. An explicit conversion exists (are you missing a cast?)"
@svick: Oh, I see. Thanks for pointing that out. I think I found the problem now. Will update my answer.
Unboxing BigInteger as int throws InvalidCastException with the message “Specified cast is not valid.” Which, again, isn't the error OP reported.
Hmm... that still not the same error. I'm out of ideas. OP needs to show more code.
2

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

2 Comments

This might work, but converting between two integer types by converting to/from string is not exactly a good choice. And, in this case, it just fixes the symptoms instead of the actual problem.
You seem sort of competent, I must take you as my apprentice.
1

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.

3 Comments

What would this do for negative numbers?
Okay, when running through the bitwise operation outside of C#, it should work fine. However, inside C# it throws a system overflow exception for negative numbers. Not sure why.
Whether you're doing this in C# or VB, BigInteger big = 3_000_000_000u; (int)(big & 0xFFFFFFFF) fails because 3_000_000_000u fits in uint and is less than 0xFFFFFFFF but overflows int. One correct way to truncate to int is unchecked((int)(uint)(big & uint.MaxValue)).
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.