0 votes
1 view
ago in Java by (2.6k points)

In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?

1 Answer

0 votes
ago by (26.5k points)

Replace from String to byte[]:

String s = "some text here";

byte[] b = s.getBytes(StandardCharsets.UTF_8);

Replace from byte[] to String:

byte[] b = {(byte) 99, (byte)97, (byte)116};

String s = new String(b, StandardCharsets.US_ASCII);

You should, of course, use the right encoding signature. My patterns applied US-ASCII and UTF-8, the two most popular encodings.

...