Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll demonstrate how we can convert a String to a BigInteger. The BigInteger is commonly used for working with very large numerical values, which are usually the result of arbitrary arithmetic calculations.

2. Converting Decimal (Base 10) Integer Strings

To convert a decimal String to BigInteger, we'll use the BigInteger(String value) constructor:

String inputString = "878";
BigInteger result = new BigInteger(inputString);
assertEquals("878", result.toString());

3. Converting Non-Decimal Integer Strings

When using the default BigInteger(String value) constructor to convert a non-decimal String, like a hexadecimal number, we may get a NumberFormatException:

String inputString = "290f98";
new BigInteger(inputString);

This exception can be handled in two ways.

One way is to use the BigInteger(String value, int radix) constructor:

String inputString = "290f98";
BigInteger result = new BigInteger(inputString, 16);
assertEquals("2690968", result.toString());

In this case, we're specifying the radix, or base, as 16 for converting hexadecimal to decimal.

The other way is to first convert the non-decimal String into a byte array, and then use the BigIntenger(byte [] bytes) constructor:

byte[] inputStringBytes = inputString.getBytes();
BigInteger result = new BigInteger(inputStringBytes);
assertEquals("290f98", new String(result.toByteArray()));

This gives us the correct result because the BigIntenger(byte [] bytes) constructor turns a byte array containing the two's-complement binary representation into a BigInteger.

4. Conclusion

In this article, we looked at a few ways to convert a String to BigIntger in Java.

As usual, all code samples used in this tutorial are available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments