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

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


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


If you are a user there is a handy Charsets class:

String s = "Hello, world!";byte[] b = s.getBytes(Charsets.US_ASCII);

Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: Charsets.US_ASCII is of Charset type (not String) so you avoid checked UnsupportedEncodingException thrown only from String.getBytes(String), but not from String.getBytes(Charset).

In Java 7 there is equivalent StandardCharsets class.


There is only one character wrong in the code you tried:

Charset characterSet = Charset.forName("US-ASCII");String string = "Wazzup";byte[] bytes = String.getBytes(characterSet);               ^

Notice the upper case "String". This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:

byte[] bytes = string.getBytes(characterSet);