Turn Byte into String

Asked

Viewed 14,796 times

11

Problem:


I’m getting byte and when I try to turn into String is making a mistake.

...
byte[] msgBytes = ch.decode(hex, ch.key()); // retorna byte
String msgDecode = msgBytes.toString(); // tentando converter byte em String
System.out.println("Mensagem descriptografada [" + msgDecode + "]"); // Exibir
...

Since decode returns me a few bytes, I used the msgBytes.toString(), I believe that conversion is not done in this way. Someone knows why you return to me [@549498794.

  • 1

    What’s in ch?

  • ch is my object, ChaveAES ch = new ChaveAES(), ChaveAES it’s my class that makes Encode and Decode and other tasks.

2 answers

11


Returned [@549498794 because the method toString of a array just use the toString class standard Object.

To convert an array of bytes to String it is possible to use the class constructor String which it receives, in addition to the byte array, encoding to be used.

Example:

String msgDecode  = new String(msgBytes, "UTF-8");

It is also possible to use the constructor without the second parameter, but in this case Java will use the encoding operating system standard, which may decrease the interoperability of your code with other platforms.

  • Thanks, it worked. I ended up making this mess because I used the String x = "teste"; x.getBytes() then I thought the toString() would return a String.

3

The problem is using the method toString() from the byte array, as I’ve commented here before. Read the documentation and you will understand how the toString.

The solution is to build a new String from the byte array, thus:

...
byte[] msgBytes = ch.decode(hex, ch.key()); // retorna byte
String msgDecode = new String(msgBytes); // tentando converter byte em String
System.out.println("Mensagem descriptografada [" + msgDecode + "]"); // Exibir
...

Again, try to query the javadoc of the classes you are using, there is a lot of useful information there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.