Converting byte array containing ASCII characters to a String

81,730

Solution 1

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.

Solution 2

String aString = new String(yourByteArray);

or

String aString = new String(yourByteArray, "aCharSet"); 
//Replacing "aCharSet" with the appropriate chararacter set

Easy See docs

Share:
81,730

Related videos on Youtube

user1118764
Author by

user1118764

Updated on July 09, 2022

Comments

  • user1118764
    user1118764 almost 2 years

    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!

  • user1118764
    user1118764 over 10 years
    Thanks! That worked! Just needed to add in throw/catch blocks or Eclipse will complain
  • Toby
    Toby over 5 years
    If op wants to convert *from" ASCII, then shouldn't this be new String(myByteArray, "ISO-8859-1");? (Assuming 8-bit ASCII/ISO-LATIN rather rather than old 7-bit)