3

What would be the best way to convert a 50-digit String to a BigInteger in Java? It doesn't have a valueOf(String) method, and I can't convert to Long because it's too small.

Jorn
  • 20,612
  • 18
  • 79
  • 126

4 Answers4

14

It does have a BigInteger(String) constructor :-)

String S = "12345678901234567890123456789012345678901234567890";
BigInteger bi = new BigInteger(S);
ChssPly76
  • 99,456
  • 24
  • 206
  • 195
2

How about...

BigInteger bi = new BigInteger(my50DigitString);

All those Xxx.valueOf() methods are alternatives to constructors because they allow for returning shared, cached copies. Constructors, by definition, return a new instance every time. So valueOf() are a nice optimization, but the designers apparently didn't find it interesting to provide a BigInteger.valueOf(String) method. You'll have to use a one of the constructors in this case.

John M
  • 13,053
  • 3
  • 27
  • 26
1

BigInteger has a constructor that takes a String.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

Have you tried

BigInteger i = new BigInteger(s);
David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125