user3317823
user3317823

Reputation: 57

convert a string holding byte array values to byte array

I'm reading messages from a TCP connection. The sender is sending a byte array but the BufferedReader reads it as a string. How can I convert the message to a byte array so I can then convert it to the actual message?

Say I want to send "hello". I use

String message = "hello"
byte[] byteData = message.getBytes();

I then send the message. It's received as a string of, say, 0Bf3f3. I need to convert it back to "hello".

Upvotes: 0

Views: 90

Answers (3)

Edwin Torres
Edwin Torres

Reputation: 2854

This is how to convert a byte array back to a String:

String message = "hello";
byte[] byteData = message.getBytes();
String retMessage = new String(byteData); // <===

Upvotes: 0

Iszlai Lehel
Iszlai Lehel

Reputation: 231

Use buffered input stream for byte data.

Upvotes: 0

Danstahr
Danstahr

Reputation: 4309

java.lang.String provides a constructor which takes an array of bytes. However, you need to keep in mind that the charset can be different at the receiver and sender side. For more details, see the javadoc.

Upvotes: 2

Related Questions