1

I am sending a message from one device to another using MQTT client/broker. The message is exchanged (sent and received) between the two devices as String succesfully.

However, on the MQTT-Broker (i.e.: the server) the message characters are received as ASCII numbers within a string.

For example if I send:

"This is a test"

On the broker it show:

"84,104,105,115,32,105,115,32,97,32,116,101,115,116,10"

Using Java, I need a way to convert this string of ASCII back to string on the server for further process.

How to do that ? thanks

4
  • You need to review your encoding settings. If both server and client have the same encoding during exchange, you should be able to receive the same information in same string form. Commented Mar 2, 2017 at 14:20
  • Some people really love to down-vote others Commented Mar 2, 2017 at 14:30
  • 2
    Yes they do. Have an up vote from me :) SO is a great site but unfortunately it attracts a lot of pretentious ******s. They are usually old, ugly or just plain cocky. Or all 3 (you know who you are ;) ). You just have to put up with it and hope for an answer before the trolls ruin your post. Commented Mar 2, 2017 at 14:46
  • @TedTrippin: Thank you for your understanding, and yes this is a GREAT site. By asking, for example, my "dumb" question, all I am trying to do really is to make this site better for me and others. I don't mind the downvote as long as it's justified. Otherwise it is just not a constructive critic. Commented Mar 6, 2017 at 11:59

3 Answers 3

2

Convert the string to a byte[] and create a new string using the byte[]

String str = "84,104,105,115,32,105,115,32,97,32,116,101,115,116,10";
String[] chars = str.split(",");
byte[] bytes = new byte[chars.length];
for (int i = 0; i < chars.length; i++) {
  bytes[i] = Byte.parseByte(chars[i]);
}
return new String(bytes);
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn’t new String specify a Charset?
Agree with @VGR, without one you are playing default charset roulette.
1

You can break the string using StringTokenizer with delimiter as comma and then iterate on each of them and use Character.toString ((char) i);

Comments

0

You can use stream as well for this, if you can use java-8

String str = Stream.of("84,104,105,115,32,105,115,32,97,32,116,101,115,116,10".split(","))
        .map(ch -> (char) Integer.valueOf(ch).intValue())
        .collect(StringBuilder::new,
                StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
System.out.println(str); // This is a test

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.