简体   繁体   English

Java字符串到字节数组的错误转换

[英]Java String to array of bytes wrong conversion

I have a client server Java code and the client is reading in a string "input" and it should then decrypt it, the decryption function needs an array of bytes, so I need to convert the string to array of bytes, which is done using "getBytes()" function, however it seems that this function is modifying the String! 我有一个客户端服务器Java代码,客户端正在读取字符串“输入”,然后应该对其解密,解密函数需要一个字节数组,因此我需要将字符串转换为字节数组,使用“ getBytes()”函数,但是似乎该函数正在修改String! How can I convert the string into an array of bytes without changing its content. 如何在不更改其内容的情况下将字符串转换为字节数组。

   String input = inputline.substring(66, inputline.length());
   System.out.println("Read message +"+input+"+");
   byte[] bx = input.getBytes(Charset.forName("UTF-8"));
   System.out.println("Read message +"+bx.toString()+"+");
   System.out.println("Read message +"+bx+"+");

the output of the code snippet is as follows: 代码段的输出如下:

Read message +[B@161cd475+ 阅读消息+ [B @ 161cd475 +

Read message +[B@4e25154f+ 阅读消息+ [B @ 4e25154f +

Read message +[B@4e25154f+ 阅读消息+ [B @ 4e25154f +

Try writing a for loop to print out the results. 尝试编写for循环以打印出结果。 I believe Java is spitting out a random memory value for your output. 我相信Java会为您的输出吐出一个随机的内存值。

(int i = 0; s <= bx.length;i++)
{
 System.out.println("Read message +" + bx[i].toString() + "+");
 System.out.println("Read message +" + bx + "+");
}

Not sure if my for loop is correct, but it may give you something to work with. 不知道我的for循环是否正确,但是可能会给您一些帮助。 I hope this helps. 我希望这有帮助。

This should work for you. 这应该为您工作。 I needed to make a String object from the byte array... 我需要从字节数组制作一个String对象...

String inputline = "[B@161cd475";
String input = inputline.substring(0, inputline.length());
System.out.println("Read message +"+input+"+");
byte[] bx = input.getBytes();

// Convert to String object
String tmp = new String(bx);
// Print statements.
System.out.println("Read message +" + tmp + "+");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM