简体   繁体   中英

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:

在此处输入图片说明

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!

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

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM