32

我将 a 转换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); 

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

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

4

9 回答 9

27

你想用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()and的重载,否则您可能会遇到编码问题。String(byte[])

于 2010-06-12T10:59:22.400 回答
8

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

于 2010-06-12T10:44:44.793 回答
8

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

(另请注意,您对字节的转换并未明确指定字符编码并且取决于平台 - 这可能是进一步的悲痛之源)

于 2010-06-12T10:44:52.267 回答
7

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

BigInteger m = new BigInteger(bytemsg); 
String mStr = "" + m;  // mStr now contains string representation of m.
于 2013-10-22T17:17:48.383 回答
2

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

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

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

(我意识到这个线程是旧的)

于 2013-06-22T11:56:39.203 回答
1

扭转

byte[] bytemsg=msg.getBytes(); 

您可以使用

String text = new String(bytemsg); 

使用 BigInteger 只会使事情复杂化,实际上不清楚为什么要使用 byte[]。打算用 BigInteger 或 byte[] 做什么?重点是什么?

于 2010-06-12T11:44:54.140 回答
0

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html

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

于 2010-06-12T10:46:26.597 回答
0
String input = "0101";
BigInteger x = new BigInteger ( input , 2 );
String output = x.toString(2);
于 2012-07-27T14:42:23.630 回答
0

//如何解决 BigDecimal & BigInteger 并返回一个字符串。

  BigDecimal x = new BigDecimal( a );
  BigDecimal y = new BigDecimal( b ); 
  BigDecimal result = BigDecimal.ZERO;
  BigDecimal result = x.add(y);
  return String.valueOf(result); 
于 2018-03-17T22:24:05.487 回答