English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java program converts byte array to hexadecimal

Comprehensive Java Examples

In this program, you will learn different methods to convert byte arrays to hexadecimal in Java.

Example1Convert the byte array to a hexadecimal value

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.

Example2Use byte operations to convert byte arrays to hexadecimal values

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.

Comprehensive Java Examples