如何在java中将BigInteger转换为String [英] How to convert BigInteger to String in java
本文介绍了如何在java中将BigInteger转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将字符串
转换为 BigInteger
,如下所示:
I converted a String
to BigInteger
as follows:
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()
但是这给了我想要的结果。
Now I want my string back. I'm using m.toString()
but that's giving me the desired result.
为什么?错误在哪里,我该怎么办?
Why? Where is the bug and what can I do about it?
推荐答案
String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
我理解的方式是你正在进行以下转换:
The way I understand it is that you're doing the following transformations:
String -----------------> byte[] ------------------> BigInteger
String.getBytes() BigInteger(byte[])
你想要反向:
BigInteger ------------------------> byte[] ------------------> String
BigInteger.toByteArray() String(byte[])
请注意,您可能需要使用 String.getBytes()
和 String(byte [])
的重载来指定显式编码,否则你可能会遇到编码问题。
Note that you probably want to use overloads of String.getBytes()
and String(byte[])
that specifies an explicit encoding, otherwise you may run into encoding issues.
这篇关于如何在java中将BigInteger转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文