乐闻世界logo
搜索文章和话题

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

1个答案

1

In Java, converting a string to an ASCII byte array can be achieved by using the getBytes() method of the String class. This method encodes the string using the default character set or a specified character set. For ASCII encoding, using the 'US-ASCII' character set is recommended to ensure correct conversion.

The following is a specific example demonstrating how to convert a Java string to an ASCII byte array:

java
public class Main { public static void main(String[] args) { String str = "Hello, World!"; // Define a string try { byte[] bytes = str.getBytes("US-ASCII"); // Convert string to ASCII byte array System.out.println("ASCII array:"); for (byte b : bytes) { System.out.print(b + " "); // Print each ASCII code value } } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); // Handle exception, e.g., specified character set not supported } } }

In this example, the string 'Hello, World!' is converted to the corresponding ASCII byte array. We use the getBytes("US-ASCII") method for conversion, specifying 'US-ASCII' to ensure the string is correctly encoded according to ASCII codes. The output will display the ASCII code values for each character.

If you do not specify a particular character set, getBytes() will use the JVM's default character set, which may not be 'US-ASCII'. To avoid encoding issues, it is best to explicitly specify the character set. If your environment defaults to ASCII encoding, you can omit specifying the encoding and directly use str.getBytes().

Additionally, handling the UnsupportedEncodingException exception is important, although using 'US-ASCII' typically does not throw this exception because all Java platforms support this character set. However, it is a good practice to handle it in case you use other character sets that might not be supported.

2024年7月30日 00:32 回复

你的答案