Convert a String to a BigInteger in Java
Last Updated :
12 Feb, 2024
In Java, the BigInteger class is a part of the java.math package and is designed to handle arbitrary precision integers. Unlike primitive data types such as int or long, which have fixed size limits, BigInteger can represent integers of any size, limited only by the available memory.
Example of String to BigInteger Conversion
Given a String, and converting it into BigInteger Number.
Example 1: Input String: “12345678901234578901201234567890”
Output BigInteger: 12345678901234578901201234567890
Example 2: Hexadecimal String: “1b4a5c6d7e8f”
Output BigInteger: 30006192209551
How to Convert a String to a BigInteger in Java?
There are certain methods to convert String to BigInteger in Java as mentioned below:
- Using BigInteger(String) constructor
- using valueOf() method
1. Convert String into BigInteger Using Constructor
Below is the implementation of the above method:
Java
import java.math.BigInteger;
class GFG {
public static void main (String[] args) {
String numberStr = "12345678901234578901201234567890" ;
BigInteger bigInt = new BigInteger(numberStr);
System.out.println( "String: " + numberStr);
System.out.println( "BigInteger: " + bigInt);
}
}
|
Output
String: 12345678901234578901201234567890
BigInteger: 12345678901234578901201234567890
2. Convert using BigInteger.valueOf() method
Below is the implementation of BigInteger.valueOf() method:
Java
import java.io.*;
import java.math.BigInteger;
class GFG {
public static void main(String[] args)
{
String numberStr = "987654323245129963" ;
BigInteger bigInt = BigInteger.valueOf(Long.parseLong(numberStr));
System.out.println( "String: " + numberStr);
System.out.println( "BigInteger: " + bigInt);
}
}
|
Output
String: 987654323245129963
BigInteger: 987654323245129963
Non-Decimal Integer Strings to BigInteger in Java
Similar to Decimal Number ( Number with Base 10 ) we can convert other number format like Base-2 (Binary), Base-8 (Octal) , Base-16(Hexadecimal) , etc.
Below is the implementation explaining the method for doing this conversion:
Java
import java.io.*;
import java.math.BigInteger;
class GFG {
public static void main(String[] args)
{
String hexString = "1b4a5c6d7e8f" ;
BigInteger bigInt
= new BigInteger(hexString, 16 );
System.out.println( "Hexadecimal String: " + hexString);
System.out.println( "Equivalent BigInteger: " + bigInt);
}
}
|
Output
Hexadecimal String: 1b4a5c6d7e8f
Equivalent BigInteger: 30006192209551
Explaination of the above Program:
In the above example we are using BigInteger constructor to convert a string hexString which contain a String Number of Base 16. It explain the fact that if we want to convert string str with base x then we can use the syntax BigInteger res = new BigInteger( str, x );
Share your thoughts in the comments
Please Login to comment...