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
2010-10-07 02:05:30
+1
A:
Use the BigInteger constructor that takes a string:
int intValue = 123;
BigInteger bigIntValue = new BigInteger(Integer.toString(intValue));
Justin Niessner
2010-10-07 02:08:31
Ok, fine. Go to bed.
jjnguy
2010-10-07 02:09:27
@Justin - *sigh* Fine. If I have to. :-P
Justin Niessner
2010-10-07 02:11:25
woooo! battle of the Justins!
Tony Ennis
2010-10-07 02:34:31
@Tony - Sorry to disappoint, but no battle. Just an off site Twitter discussion. Haha.
Justin Niessner
2010-10-07 02:56:15
+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
2010-10-07 02:09:17
I haven't done Java in a while, but: you want `.longValue()`, not `.intValue()`, right?
Michael Petrotta
2010-10-07 02:16:15
@Mich, no. If it is an integer, Java will automatically expand it for you. (The OP says he has an Integer)
jjnguy
2010-10-07 02:17:27
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
2010-10-07 02:18:45