Home > Java > javaTutorial > How to Efficiently Convert a Byte Array to Hexadecimal in Java?

How to Efficiently Convert a Byte Array to Hexadecimal in Java?

Linda Hamilton
Release: 2024-11-29 02:49:09
Original
527 people have browsed it

How to Efficiently Convert a Byte Array to Hexadecimal in Java?

Converting a Byte Array to Hexadecimal in Java

One can encounter a situation where they need to convert an array of bytes into their corresponding hexadecimal values. Java provides a straightforward method to achieve this conversion efficiently.

Java Implementation

The most concise approach to convert a byte array to hexadecimal is to utilize the StringBuilder class:

byte[] bytes = {-1, 0, 1, 2, 3 };
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
    sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
Copy after login

This code iterates through each byte in the array, converts it to a hexadecimal string with leading zeros (X), and appends it to the string builder. The resulting string contains the hexadecimal values separated by spaces.

Alternative Interpretation

Some scenarios may require converting a string array of decimal values to hexadecimal strings. This can be achieved as follows:

String[] arr = {"-1", "0", "10", "20" };
for (int i = 0; i < arr.length; i++) {
    arr[i] = String.format("%02x", Byte.parseByte(arr[i]));
}
System.out.println(java.util.Arrays.toString(arr));
Copy after login

This code converts each string in the array to a byte, then uses the String.format method to create a hexadecimal string with leading zeros.

Considerations

Note that Integer.toHexString(int) can also be used, but be cautious of sign extension when working with negative byte values. Alternatively, the String.format solution is more reliable and flexible.

The above is the detailed content of How to Efficiently Convert a Byte Array to Hexadecimal 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