Home >Java >javaTutorial >How to Efficiently Convert 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.
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());
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.
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));
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.
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!