Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte array containing ASCII characters to a String

Tags:

I have a byte array that consists of ASCII characters that I wish to convert to a String. For example:

byte[] myByteArray = new byte[8]; for (int i=0; i<8; i++) {     byte[i] = (byte) ('0' + i); } 

myByteArray should contain a string "12345678" after the loop. How do I get this string into a String variable?

Thanks!

like image 449
user1118764 Avatar asked Sep 03 '13 02:09

user1118764


People also ask

How do I convert ASCII to string?

To convert ASCII to string, use the toString() method. Using this method will return the associated character.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

Can byte array be stored in a string?

String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java. String str = new String(byteArray, StandardCharsets. UTF_8);


1 Answers

Use

new String(myByteArray, "UTF-8"); 

String class provides a constructor for this.

Side note:The second argument here is the CharSet(byte encoding) which should be handled carefully. More here.

like image 66
rocketboy Avatar answered Oct 02 '22 18:10

rocketboy