Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...