如何在java中将BigInteger转换为String [英] How to convert BigInteger to String in java

查看:462
本文介绍了如何在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?

推荐答案

你想使用 BigInteger.toByteArray()

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆