darksky
darksky

Reputation: 21019

How to convert String into Byte and Back

For converting a string, I am converting it into a byte as follows: byte[] nameByteArray = cityName.getBytes();

To convert back, I did: String retrievedString = new String(nameByteArray); which obviously doesn't work. How would I convert it back?

Upvotes: 6

Views: 7963

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

which obviously doesn't work.

Actually that's exactly how you do it. The only thing that can go wrong is that you're implicitly using the platform default encoding, which could differ between systems, and might not be able to represent all characters in the string.

The solution is to explicitly use an encoding that can represent all characts, such as UTF-8:

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

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

Upvotes: 5

anubhava
anubhava

Reputation: 785128

What characters are there in your original city name? Try UTF-8 version like this:

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

Upvotes: 10

Related Questions