如何在java中将BigInteger转换为String

我将String转换为BigInteger如下:

 Scanner sc=new Scanner(System.in); System.out.println("enter the message"); String msg=sc.next(); byte[] bytemsg=msg.getBytes(); BigInteger m=new BigInteger(bytemsg); 

现在我想要我的字符串。 我正在使用m.toString()但这给了我想要的结果。

为什么? 错误在哪里,我该怎么办呢?

你想使用BigInteger.toByteArray()

 String msg = "Hello there!"; BigInteger bi = new BigInteger(msg.getBytes()); System.out.println(new String(bi.toByteArray())); // prints "Hello there!" 

我理解它的方式是你正在进行以下转换:

  String -----------------> byte[] ------------------> BigInteger String.getBytes() BigInteger(byte[]) 

而你想要反过来:

  BigInteger ------------------------> byte[] ------------------> String BigInteger.toByteArray() String(byte[]) 

请注意,您可能希望使用指定显式编码的String.getBytes()String(byte[])重载,否则可能会遇到编码问题。

使用m.toString()String.valueOf(m) 。 String.valueOf使用toString()但是为null安全。

为什么不使用BigInteger(String)构造函数? 这样,通过toString()往返应该可以正常工作。

(另请注意,您对字节的转换没有明确指定字符编码并且与平台有关 – 这可能是进一步的悲痛根源)

您还可以使用Java的隐式转换:

 BigInteger m = new BigInteger(bytemsg); String mStr = "" + m; // mStr now contains string representation of m. 

使用字符串构造BigInteger时,必须将字符串格式化为十进制数字。 您不能使用字母,除非您在第二个参数中指定基数,您可以在基数中指定最多36个。 36将仅为您提供字母数字字符[0-9,az],因此如果使用此字符,您将没有格式化。 你可以创建:new BigInteger(“ihavenospaces”,36)然后转换回来,使用.toString(36)

但要保持格式化:使用几个人提到的byte []方法。 这会将格式化的数据打包成最小的大小,并允许您轻松跟踪字节数

这对于RSA公钥加密系统示例程序应该是完美的,假设您保持消息中的字节数小于PQ的字节数

(我意识到这个线程很旧)

扭转

 byte[] bytemsg=msg.getBytes(); 

您可以使用

 String text = new String(bytemsg); 

使用BigInteger只会使事情变得复杂,实际上不清楚为什么要使用byte []。 与BigInteger或byte []有什么关系? 有什么意义?

http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html

每个对象在Java中都有一个toString()方法。

 String input = "0101"; BigInteger x = new BigInteger ( input , 2 ); String output = x.toString(2); 

//如何解决BigDecimal和BigInteger并返回一个String。

  BigDecimal x = new BigDecimal( a ); BigDecimal y = new BigDecimal( b ); BigDecimal result = BigDecimal.ZERO; BigDecimal result = x.add(y); return String.valueOf(result);