137
votes

I was wondering if there was any way to convert a variable of type Integer, to BigInteger. I tried typecasting the Integer variable, but i get an error that says inconvertible type.

3
you have asked a few questions about BigInteger that would be solved fairly easily by reading the Javadocs. Follow the link in my answer, and check out all of the methods and constructors that BigInteger has. - jjnguy

3 Answers

250
votes

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

0
votes

converting Integer to BigInteger

        BigInteger big_integer = BigInteger.valueOf(1234);

converting BigInteger back to Integer

int integer_value = big_integer.intValue();

converting BigInteger back to long

long long_value = big_integer.longValue();

converting string to BigInteger

        BigInteger bigInteger = new BigInteger("1234");

converting BigInteger back to string

        String string_expression = bigInteger.toString();
-5
votes

You can do in this way:

    Integer i = 1;
    new BigInteger("" + i);