Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte to string in Java

Tags:

I use below code to convert byte to string:

System.out.println("string " + Byte.toString((byte)0x63)); 

Why it print "string 99". How to modify to let it print "string c"?

like image 262
brian Avatar asked Dec 28 '11 09:12

brian


People also ask

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. 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.

Can we convert byte array to string in Java?

A byte is 8 bits of binary data so do byte array is an array of bytes used to store the collection of binary data. There are multiple ways to change byte array to String in Java, you can either use methods from JDK, or you can use open-source complementary APIs like Apache commons and Google Guava.


1 Answers

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII")); 

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.

like image 59
Michael Borgwardt Avatar answered Oct 15 '22 13:10

Michael Borgwardt