con*_*nya 29 java string cryptography biginteger
我转换一个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);
Run Code Online (Sandbox Code Playgroud)
现在我想要我的字符串.我正在使用,m.toString()但这给了我想要的结果.
为什么?错误在哪里,我该怎么办呢?
pol*_*nts 26
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(String)构造函数?这样,往返通道toString()应该可以正常工作.
(另请注意,您对字节的转换没有明确指定字符编码,并且与平台有关 - 这可能是进一步的悲痛根源)
使用m.toString()或String.valueOf(m).String.valueOf使用toString()但是为null安全.
您还可以使用Java的隐式转换:
BigInteger m = new BigInteger(bytemsg);
String mStr = "" + m; // mStr now contains string representation of m.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92128 次 |
| 最近记录: |