Transform Byte into String

6

Problem:

I am getting byte and when I try to transform to String it is giving error.

...
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 msgBytes.toString() , I believe that conversion is not done this way. Does anyone know why%% returns me.

    
asked by anonymous 27.02.2014 / 20:15

2 answers

3

Returned [@549498794 because the toString method of a array only uses the toString of the Object class.

To convert a byte array to String you can use the class constructor String that receives, in addition to the encoding bytes array to be used.

Example:

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

You can also use the constructor without the second parameter, but in this case Java will use the default encoding of the operating system, which may decrease the interoperability of your code with other platforms. p>     

27.02.2014 / 20:24
3

The problem is to use the toString() method from the byte array, as I have already commented before . Read the documentation and you will understand how toString works.

The solution is to construct a new String from the byte array, like this:

...
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 consult the javadoc of the classes you are using, there is a lot of useful information there.

    
27.02.2014 / 20:23