converting int to/from System.Numerics.BigInteger in C#

14,228

Solution 1

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

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

Solution 3

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.

Solution 4

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.

Share:
14,228
prosseek
Author by

prosseek

A software engineer/programmer/researcher/professor who loves everything about software building. Programming Language: C/C++, D, Java/Groovy/Scala, C#, Objective-C, Python, Ruby, Lisp, Prolog, SQL, Smalltalk, Haskell, F#, OCaml, Erlang/Elixir, Forth, Rebol/Red Programming Tools and environments: Emacs, Eclipse, TextMate, JVM, .NET Programming Methodology: Refactoring, Design Patterns, Agile, eXtreme Computer Science: Algorithm, Compiler, Artificial Intelligence

Updated on June 09, 2022

Comments

  • prosseek
    prosseek almost 2 years

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

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

    How can I convert int to/from System.Numerics.BigInteger in C#?

  • Feidex
    Feidex over 12 years
    @svick: Which one? I get this: "Cannot implicitly convert type 'System.Numerics.BigInteger' to 'int'. An explicit conversion exists (are you missing a cast?)"
  • Feidex
    Feidex over 12 years
    @svick: Oh, I see. Thanks for pointing that out. I think I found the problem now. Will update my answer.
  • svick
    svick over 12 years
    Unboxing BigInteger as int throws InvalidCastException with the message “Specified cast is not valid.” Which, again, isn't the error OP reported.
  • Feidex
    Feidex over 12 years
    Hmm... that still not the same error. I'm out of ideas. OP needs to show more code.
  • Feidex
    Feidex over 12 years
    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.
  • ChaosPandion
    ChaosPandion over 12 years
    You seem sort of competent, I must take you as my apprentice.
  • svick
    svick over 11 years
    What would this do for negative numbers?
  • Admin
    Admin over 11 years
    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.