0 votes
1 view
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
by (42.1k 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.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 28 in Java by Anvi (8.5k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...