Home > Java > javaTutorial > How Do I Convert Strings and Byte Arrays Using Different Encodings in Java?

How Do I Convert Strings and Byte Arrays Using Different Encodings in Java?

Patricia Arquette
Release: 2024-12-04 07:17:12
Original
172 people have browsed it

How Do I Convert Strings and Byte Arrays Using Different Encodings in Java?

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);
Copy after login

Other commonly used encodings include US-ASCII:

byte[] b = s.getBytes(StandardCharsets.US_ASCII);
Copy after login

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);
Copy after login

Similarly, for US-ASCII decoding:

String s = new String(b, StandardCharsets.US_ASCII);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template