如何在java中把BigInteger转换为String/String转换为BigInteger,并举例说明

1,561 阅读3分钟

在这篇博文中,我们将学习如何将BigInteger 从/到String ,并举例说明。

Java中的BigInteger对象

BigInteger 通常用于通过任意算术计算的结果来存储数字大值。

它被定义在java.math 包中。

存储在BigInteger 中的值比所有原始数据类型的值都要高。大整数中可以存储的最大值没有上限。

BigInteger 转换为String 是java程序员的日常工作之一。两者都是用来存储不同的值,在Java中没有办法自动转换。

几天前,我在编程中需要将BigInteger转换为Integer。要做到这一点很简单。
在我的上一篇文章中,我们讨论了BigInteger到Integer的转换,反之亦然,我们也可以做同样的转换到String。

我们将讨论以下内容

  • 如何将BigInteger转换为String
  • 如何将字符串转换为BigInteger

如何在Java中把BigInteger转换为一个字符串对象:-

我们有多种方法可以进行转换,一种方法是使用BigInteger.toString() 方法,另一种方法是在Java中使用String.valueOf()

使用toString()方法

java中的每个类都有toString 方法。

用这个方法做这件事很简单。让我们创建一个BigInteger 对象。

BigInteger 类有一个构造函数,接受String作为参数,它创建一个对象。

BigInteger bi=new BigInteger("123");

你知道每个java类都有toString方法,对于BigInteger类来说,要返回String对象。

以下是返回字符串对象的代码行

String str=bi.toString();  

下面是一个完整的例子,成功的使用案例是string ,其中包含numeric

import java.math.BigInteger;

public class Test {
    public static void main(String[] args) {
        
        //The following case works without throwing exception
        BigInteger bigIntegerdemo = new BigInteger("123");
        System.out.println(bigIntegerdemo.toString());
    }
}

输出:

123

下面是一个错误的例子,string 包含非数字的值

import java.math.BigInteger;

public class Test {
    public static void main(String[] args) {
        //The following case doest not works and throws NumberFormatException
        BigInteger bigIntegerdemo1 = new BigInteger("abc");
        System.out.println(bigIntegerdemo1.toString());

    }
}

输出在线程 "main "中抛出一个错误的Exception java.lang.NumberFormatException。对于输入字符串。"abc"

Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.math.BigInteger.(BigInteger.java:470)
	at java.math.BigInteger.(BigInteger.java:606)
	at Test.main(Test.java:14)

缺点:这种方法总是需要以字符串的形式传递数字值给BigInteger构造函数。

如果像 "abc "这样的字符串被传递,它会抛出NumberFormatException

使用toByteArray()方法

另一种方法:

  • 首先创建一个BigInteger 对象
  • 使用toByteArray() 方法转换为字节数组
  • 最后,将数组字节传递给String的字节构造函数。
BigInteger bigIntegerdemo2 = new BigInteger("123");  
  byte b[]=bigIntegerdemo2.toByteArray();  
  String s=new String(b);  

如何在Java中把字符串转换成BigInteger对象:

我们可以使用BigInteger.toByteArray() 方法将字符串转换为BigInteger对象

  • 首先,使用构造函数创建一个字符串对象
  • 通过传递字节数组来创建一个大整数String.getBytes()
  • 因此,转换为BigInteger对象
  • 如果你想,你可以使用toByteArray 方法转换为字符串。
String msg = new String ("Hi test");  
  BigInteger bi = new BigInteger(msg.getBytes());  
  System.out.println(new String(bi.toByteArray())); // prints "Hi test"  

总结

你学会了如何将字符串转换为大整数和使用多种方法转换大整数