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

farm ostrich picture farm ostrich · Apr 16, 2011 · Viewed 170.8k times · Source

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

Answer

Sebastian Paaske Tørholm picture Sebastian Paaske Tørholm · Apr 16, 2011

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");)