How to convert a Java String to an ASCII byte array?

By | July 28, 2019

Question

How to convert a Java String to an ASCII byte array?

Solution

Using the getBytes method, giving it the appropriate Charset (or Charset name).

Example:

String s = "Hello, there.";
byte[] b = s.getBytes(StandardCharsets.US_ASCII);

(Before Java 7: byte[] b = s.getBytes("US-ASCII");)

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *