Home  >  Article  >  Java  >  How Can I Convert a Java String to a Byte Array and Back?

How Can I Convert a Java String to a Byte Array and Back?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 02:47:10972browse

How Can I Convert a Java String to a Byte Array and Back?

Conversion of Java String to Byte Array

Question:

How can a Java String be converted into a byte array?

Answer:

To convert a Java String to a byte array, utilize one of the following methods:

  • byte[] b = string.getBytes(); (Platform Default Charset)
  • byte[] b = string.getBytes(Charset.forName("UTF-8")); (UTF-8 Charset)
  • byte[] b = string.getBytes(StandardCharsets.UTF_8); (Java 7 Only)

Displaying Byte Array:

The default toString() method of a byte array doesn't provide a useful representation. To view the byte array in a human-readable format, use:

  • Arrays.toString(bytes); (Commas between values)

Retrieving String from Byte Array:

To convert a byte array back to a String, use:

  • String string = new String(byte[] bytes, Charset charset); (Specify the desired charset)

Note on Character Encoding:

It's essential to understand the character encoding used when converting between strings and byte arrays. Strings in Java are internally stored using UTF-16. Using different character encodings (e.g., ASCII, UTF-8) will result in different byte array representations for the same glyphs.

The above is the detailed content of How Can I Convert a Java String to a Byte Array and Back?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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