0

I wish to convert a byte array to String but as I do so, my String has 00 before every digit got from the array.

I should have got the following result: 49443a3c3532333437342e313533373936313835323237382e303e

But I have the following:

enter image description here

Please help me, how can I get the nulls away?

I have tried the following ways to convert:

xxxxId is the byteArray

String xxxIdString = new String(Hex.encodeHex(xxxxId));

Thank you!

dorcsi
  • 295
  • 2
  • 6
  • 24

3 Answers3

5

Try something like this:

String s = new String(bytes);
s = s.replace("\0", "")

It's also posible, that the string will end after the first '\0' received, if thats the case, first iterate through the array and replace '\0' with something like '\n' and do this:

String s = new String(bytes);
s = s.replace("\n", "")

EDIT: use this for a BYTE-ARRAY:

String s = new String(bytes, StandardCharsets.UTF_8);

use this for a CHAR:

String s = new String(bytes);
28Smiles
  • 104
  • 1
  • 6
  • 1
    Thank you, I appreciate yout help a lot, it worked... :) – dorcsi Sep 26 '18 at 12:36
  • 2
    On Java 7 you can also use `new String(bytes, StandardCharsets.UTF_8);` which avoids having to catch the `UnsupportedEncodingException` – TiiJ7 Sep 26 '18 at 12:37
  • @TiiJ7 Ah, didn't knew about that! TIL. :) Was about to comment [that I can confirm it works in an online compiler, but requires a try-catch or throws](https://ideone.com/GNjt7e). EDIT: Indeed looks a lot [more compact and better](https://ideone.com/1tv3xu) without the try-catch. – Kevin Cruijssen Sep 26 '18 at 12:39
1

Try below code:

byte[] bytes = {...} 
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding

please have a look here- How to convert byte array to string and vice versa?

Ajinkya
  • 79
  • 1
  • 6
0

In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it.

 String example = "This is an example";
 byte[] bytes = example.getBytes();
 String s = new String(bytes);
Afaq Ahmed Khan
  • 2,164
  • 2
  • 29
  • 39
  • Simply posting some code isn't terribly helpful. Can you explain your code? That way others can understand and learn from your answer instead of just copying & pasting some code from the web. Also note that your code blissfully ignores charsets and may be quite fragile. – Robert Sep 26 '18 at 14:34