Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
330 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...