Home > Java > javaTutorial > body text

How can I convert byte arrays to strings and vice versa in Java?

Susan Sarandon
Release: 2024-11-09 05:19:02
Original
710 people have browsed it

How can I convert byte arrays to strings and vice versa in Java?

Byte Array Conversion

Java provides various methods to convert byte arrays to strings and vice versa. This conversion is critical for data transmission and manipulation. One common scenario involves sending byte data over a network and reconstructing it on the receiving end.

Byte Array to String Conversion

To convert a byte array to a string, the Arrays.toString() method can be used. It takes an array as input and returns a string representation of its elements enclosed in square brackets. For example:

byte[] data = new byte[] {4, 6, 8, 10};
String dataString = Arrays.toString(data); // prints [-44, 6, 8, 10]
Copy after login

String to Byte Array Conversion

However, this string representation cannot be directly converted back to a byte array. To achieve this, it's necessary to parse the individual byte values from the string. One approach is to use the String.split() method to separate the byte values and then parse them using the Byte.parseByte() method.

String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]";

String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];

for (int i = 0, len = bytes.length; i < len; i++) {
    bytes[i] = Byte.parseByte(byteValues[i].trim());
}
Copy after login

Alternative Solutions

Alternatively, the ByteBuffer class can be used to efficiently perform byte array conversions. It provides methods like wrap() to create a buffer from a byte array and array() to retrieve the underlying byte array from a buffer.

byte[] data = new byte[] {4, 6, 8, 10};

ByteBuffer buffer = ByteBuffer.wrap(data);
byte[] dataCopy = buffer.array(); // returns a copy of the original byte array
Copy after login

Note: The Arrays.toString() method can also be used with primitive arrays, such as int, double, and long, to generate a string representation of their elements. However, the conversion back to an array of primitive types requires additional parsing mechanisms, which are language-specific and vary depending on the type.

The above is the detailed content of How can I convert byte arrays to strings and vice versa 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