Converting Strings and Byte Arrays with Encodings
In Java, strings can be encoded into byte arrays, and byte arrays can be decoded into strings using different encodings.
Encoding a String into a Byte Array
To encode a string into a byte array using UTF-8 encoding:
String s = "my string"; byte[] b = s.getBytes(StandardCharsets.UTF_8);
Other commonly used encodings include US-ASCII:
byte[] b = s.getBytes(StandardCharsets.US_ASCII);
Decoding a Byte Array into a String
To decode a byte array into a string using UTF-8 decoding:
byte[] b = {(byte) 99, (byte) 97, (byte) 116}; String s = new String(b, StandardCharsets.UTF_8);
Similarly, for US-ASCII decoding:
String s = new String(b, StandardCharsets.US_ASCII);
Remember to use the appropriate encoding name for your specific use case. By leveraging these encoding methods, you can seamlessly convert between string and byte array representations with different character encodings.
The above is the detailed content of How Do I Convert Strings and Byte Arrays Using Different Encodings in Java?. For more information, please follow other related articles on the PHP Chinese website!