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!
To convert ASCII to string, use the toString() method. Using this method will return the associated character.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With