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

后端 未结 10 487
心在旅途
心在旅途 2020-12-01 04:28

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

相关标签:
10条回答
  • 2020-12-01 04:50

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

    0 讨论(0)
  • 2020-12-01 04:50

    If you are a guava 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.

    0 讨论(0)
  • 2020-12-01 04:50

    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);
    
    0 讨论(0)
  • 2020-12-01 04:51
    String s = "ASCII Text";
    byte[] bytes = s.getBytes("US-ASCII");
    
    0 讨论(0)
提交回复
热议问题