dorcsi
dorcsi

Reputation: 325

Converting byte array to String Java

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!

Upvotes: 0

Views: 18092

Answers (3)

Afaq Ahmed Khan
Afaq Ahmed Khan

Reputation: 2302

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);

Upvotes: 0

28Smiles
28Smiles

Reputation: 104

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);

Upvotes: 5

Ajinkya
Ajinkya

Reputation: 89

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?

Upvotes: 1

Related Questions