如何在java中将BigInteger转换为String

con*_*nya 29 java string cryptography biginteger

我转换一个StringBigInteger如下:

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); 
Run Code Online (Sandbox Code Playgroud)

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

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

pol*_*nts 26

你想用 BigInteger.toByteArray()

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

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

  String  -----------------> byte[] ------------------> BigInteger
          String.getBytes()         BigInteger(byte[])
Run Code Online (Sandbox Code Playgroud)

而你想要反过来:

  BigInteger ------------------------> byte[] ------------------> String
             BigInteger.toByteArray()          String(byte[])
Run Code Online (Sandbox Code Playgroud)

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

  • 刚刚在今天早些时候尝试过,它似乎没有用.我经过多次转换后检索一个BigInteger,然后尝试这样做,它给了我一个垃圾序列. (3认同)

Bri*_*new 8

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

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

  • 如果我使用像BigInteger(String)构造函数我得到异常:java.lang.NumberFormatException (2认同)

kro*_*ock 7

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

  • 如果BigInteger确实表示一个String,那么将它转换为byte []或BigInteger似乎没有任何值.你为什么要那样做? (2认同)

Wit*_*eld 7

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

BigInteger m = new BigInteger(bytemsg); 
String mStr = "" + m;  // mStr now contains string representation of m.
Run Code Online (Sandbox Code Playgroud)