25

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!

2 Answers 2

48

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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)
4
String aString = new String(yourByteArray);

or

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

Easy See docs

1 Comment

Thanks! That worked! Just needed to add in throw/catch blocks or Eclipse will complain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.