2

I'm connecting to a bluetooth device that answers to some parameters I send it, but as a response I read from a socket like this:

String data = dIn.readLine();

Where dIn is a:

DataInputStream dIn = new DataInputStream(socket.getInputStream());

The thing is that I receive the data, but it's a byte array read on a string. How can I convert that string that contains my byte array into a String with the correct hexadecimal values?

Thank you in advance.

1
  • Can you give an example of the data you're receiving, and how you think it should look? Commented Oct 17, 2011 at 12:14

3 Answers 3

7

It's unclear whether you're trying to actually decode a text string which you've got as a byte array, or whether you want a text representation (in hex) of arbitrary binary data. For the first you'd use:

String text = new String(data, 0, data.length, "ASCII");

For the second you could use something like Apache Commons Codec:

String text = Hex.encodeHexString(data);
Sign up to request clarification or add additional context in comments.

2 Comments

More or less this is what I needed... But not exactly.
@Sonhja: Ask a more specific question, get a more specific answer :)
0

Have a look at String's Format function. If you specify the format as "%X", it will be returned as a hex string

You will have to iterate through the byte array to convert each, as the above function accepts only primitive numeric types.

1 Comment

%X for uppercase alpha chars or %x for lowercase alpha chars.
0

Wrap the DataInputStream in an InputStreamReader.

DataInputStream.readLine() is deprecated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.