English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn different methods to convert byte arrays to hexadecimal in Java.
public class ByteHex { public static void main(String[] args) { byte[] bytes = {10, 2, 15, 11}; for (byte b : bytes) { String st = String.format("%02X", b); System.out.print(st); } } }
When running the program, the output is:
0A020F0B
In the above program, we have a byte array named bytes. To convert the byte array to a hexadecimal value, we iterate over each byte in the array and use String's format().
We use %02Print the two positions of the hexadecimal value (X)2), and store it in the string st.
For the conversion of large byte arrays, this is a relatively slow process. We can use the byte operations shown below to greatly improve the execution speed.
public class ByteHex { private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2]= hexArray[v >>> 4]; hexChars[j * 2 + 1]= hexArray[v & 0x0F]; } return new String(hexChars); } public static void main(String[] args) { byte[] bytes = {10, 2, 15, 11}; String s = bytesToHex(bytes); System.out.println(s); } }
The output of this program is as follows1Same.