Converting String to BigInteger in Java – 在Java中把字符串转换为大整数

最后修改: 2021年 7月 12日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

在本教程中,我们将演示如何将一个String转换为BigIntegerBigInteger通常用于处理非常大的数值,这些数值通常是任意算术计算的结果。

2. Converting Decimal (Base 10) Integer Strings

2.转换十进制(基数10)的整数串

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

要将一个十进制的String转换为BigInteger,我们将使用BigInteger(String value)构造函数

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

3. Converting Non-Decimal Integer Strings

3.转换非小数的整数字符串

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

当使用默认的BigInteger(String value)构造函数转换非十进制的String时,例如十六进制的数字,我们可能会得到一个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:

一种方法是使用BigInteger(String value, int radix) 构造函数

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.

在这种情况下,我们指定radix,或基数为16,用于将十六进制转换为十进制。

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

另一种方法是首先非十进制字符串转换为一个字节数组,然后使用BigIntenger(byte [] bytes)构造器

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.

这给了我们正确的结果,因为BigIntenger(byte [] bytes)构造函数将一个包含二进制补码的byte数组变成了BigInteger

4. Conclusion

4.总结

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

在这篇文章中,我们研究了在Java中把String转换为BigIntger的几种方法。

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

像往常一样,本教程中使用的所有代码样本都可以在GitHub上找到