Java convert BigInteger to long
Tags: BigInteger BigInteger longValueExact BigInteger longValue long
In this Java core tutorial we learn how to use the java.math.BigInteger.longValueExact() and java.math.BigInteger.longValue() method to convert a BigInteger object into a long value.
How to convert BigInteger object to long value
To convert a BigInteger value into a long value we can use the method java.math.BigInteger.longValueExact(). This method also checks the value of BigInteger if it is out of range of long then an ArithmeticException is thrown.
ConvertBigIntegerToLongExample1.java
import java.math.BigInteger;
public class ConvertBigIntegerToLongExample1 {
public static void main(String... args) {
BigInteger value = new BigInteger("1122334455");
long longValue = value.longValueExact();
System.out.println("BigInteger value: " + value);
System.out.println("long value: " + longValue);
}
}
BigInteger value: 1122334455
long value: 1122334455
We also can use the java.math.BigInteger.longValue() method which casts the BigInteger value to a long.
ConvertBigIntegerToLongExample2.java
import java.math.BigInteger;
public class ConvertBigIntegerToLongExample2 {
public static void main(String... args) {
BigInteger value = new BigInteger("998877665544");
long longValue = value.longValue();
System.out.println("BigInteger value: " + value);
System.out.println("long value: " + longValue);
}
}
BigInteger value: 998877665544
long value: 998877665544
Happy Coding 😊