How to convert string to byte and vice versa

To convert a string, I convert it to byte as follows: byte[] nameByteArray = cityName.getBytes();

To convert back, I did: String retrievedString = new String(nameByteArray);which obviously does not work. How can I convert it back?

+5
source share
2 answers

What characters are in your original city name? Try the UTF-8 version as follows:

byte[] nameByteArray = cityName.getBytes("UTF-8");
String retrievedString = new String(nameByteArray, "UTF-8");
+9
source

which obviously does not work.

Actually, that’s how you do it. The only thing that may go wrong is that you implicitly use the standard encoding of the platform, which may vary between systems and may not display all characters in a string.

, , , UTF-8:

byte[] nameByteArray = cityName.getBytes("UTF-8");

String retrievedString = new String(nameByteArray, "UTF-8");
+5

All Articles