Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String into Byte and Back

Tags:

java

string

byte

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?

like image 450
darksky Avatar asked Sep 13 '11 12:09

darksky


People also ask

Can I convert string to byte in Java?

How to convert String to byte[] in Java? In Java, we can use str. getBytes(StandardCharsets. UTF_8) to convert a String into a byte[] .

Is byte [] same as string?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.


1 Answers

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");
like image 148
anubhava Avatar answered Oct 18 '22 05:10

anubhava