views:

96

answers:

3

Hello, 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  A: 

You can use the String constructor from BigInteger like so:

int regularInt = 321312; // some value
BigInteger bigInt = new BigInteger(String.valueOf(regularInt));
jjnguy
+1  A: 

Use the BigInteger constructor that takes a string:

int intValue = 123;
BigInteger bigIntValue = new BigInteger(Integer.toString(intValue));
Justin Niessner
Ok, fine. Go to bed.
jjnguy
@Justin - *sigh* Fine. If I have to. :-P
Justin Niessner
woooo! battle of the Justins!
Tony Ennis
@Tony - Sorry to disappoint, but no battle. Just an off site Twitter discussion. Haha.
Justin Niessner
+7  A: 

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.

Fly
Yup, this is probably what he wants.
jjnguy
I haven't done Java in a while, but: you want `.longValue()`, not `.intValue()`, right?
Michael Petrotta
@Mich, no. If it is an integer, Java will automatically expand it for you. (The OP says he has an Integer)
jjnguy
That would work just as well. On an Integer the intValue() will not overflow, so the call to valueOf will simply widen the int to a long. There's no noticeable difference between using longValue() and intValue() in this example, but if he started with a Long, he would want to use longValue().
Fly