1

How do I convert a byte array to a string? Is this the correct syntax?

byteArray.toString();
Adrian Toman
11.5k6 gold badges50 silver badges63 bronze badges
asked Nov 25, 2010 at 9:26
3
  • Have you tried it? Was there a problem? Commented Nov 25, 2010 at 9:29
  • 1
    what does the compiler say? "Computer Says No!"??? Commented Nov 25, 2010 at 9:29
  • @ Mitch Wheat i am getting different anwsers for bytearray.toString() and public void convertByteArrayToString() { byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46}; String value = new String(byteArray); System.out.println(value); } Commented Nov 25, 2010 at 10:32

2 Answers 2

3

The Best way to convert bytearray to String is

public void convertByteArrayToString(Charset encoding) {
 byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
 String value = new String(byteArray, encoding);
 System.out.println(value);
 }
answered Nov 25, 2010 at 9:32
Sign up to request clarification or add additional context in comments.

4 Comments

String(byte[]) uses the system's default encoding. You should use String(byte[], String) to specify an encoding, which depends on what your encoding your bytes are in.
@Nick i am getting an error String value = new String(byteArray, "text/xml; charset=utf-8"); as unsupported encoding exception
@Nick also tried String value = new String(byteArray, "charset=utf-8");
It should be a string such as UTF-8. See download.oracle.com/javase/1.4.2/docs/api/java/nio/charset/… for some standard charsets.
3

You need to supply an encoding, otherwise you get the system default encoding, essentially a random value.

String value = new String(byteArray, encoding);
answered Dec 11, 2012 at 12:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.