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.
Asked
Active
Viewed 2.6e+01k times
145
-
13you 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 Oct 07 '10 at 02:09
3 Answers
256
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.

jbindel
- 5,535
- 2
- 25
- 38
-
2@Mich, no. If it is an integer, Java will automatically expand it for you. (The OP says he has an Integer) – jjnguy Oct 07 '10 at 02:17
-
1That 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(). – jbindel Oct 07 '10 at 02:18
-
It's also been suggested that dropping `intValue()` looks nice, and modern versions of Java will auto-unbox the `Integer` into an `int` which is then used. The automatic unboxing only hides that detail from you. – jbindel Nov 02 '12 at 15:11
-
-
3Amar, that would be similar to other String-based approaches. The key thing to avoid here is any generation or parsing of Strings. – jbindel Aug 05 '13 at 03:27
-
2It's not that using a String would give you the wrong answer, but it's extra work for the computer. For example, you can go the house next door by walking next door, or you could go in the opposite direction and go nearly all the way around the globe. You'd still get there, and if you have a fast rocket-plane, you might not notice the time it took, but it's wasteful, and it does take some time longer. – jbindel Aug 05 '13 at 03:30
-
The best way is to use : `BigInteger bi = BigInteger.valueOf(myInteger.longValue());` and also to avoid bug detection by code quality platforms like SonarQube. – Mohammed Réda OUASSINI May 12 '16 at 10:08
-
1
2
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();

Fabala Dibbasey
- 35
- 4
-4
You can do in this way:
Integer i = 1;
new BigInteger("" + i);

Giorgios Karagounis
- 21
- 4
-
8You can, but why would you? A much better solution is proposed in the already accepted answer. – Colin Jan 30 '18 at 11:50
-
Making strings to perform integer math wastes more CPU cycles than you would care to count. – jbindel Jan 31 '18 at 16:02