Java Program to Convert Byte Array to Hexadecimal

In this program, you’ll learn different techniques to convert byte array to hexadecimal in Java.

Example 1: Convert Byte Array to Hex value

  1. public class ByteHex {
  2. public static void main(String[] args) {
  3. byte[] bytes = {10, 2, 15, 11};
  4. for (byte b : bytes) {
  5. String st = String.format("%02X", b);
  6. System.out.print(st);
  7. }
  8. }
  9. }

When you run the program, the output will be:

0A020F0B

In the above program, we have a byte array named bytes. To convert byte array to hex value, we loop through each byte in the array and use String‘s format().

We use %02X to print two places (02) of Hexadecimal (X) value and store it in the string st.

This is relatively slower process for large byte array conversion. We can dramatically increase the speed of execution using byte operations shown below.


Example 2: Convert Byte Array to Hex value using byte operations

  1. public class ByteHex {
  2. private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
  3. public static String bytesToHex(byte[] bytes) {
  4. char[] hexChars = new char[bytes.length * 2];
  5. for ( int j = 0; j < bytes.length; j++ ) {
  6. int v = bytes[j] & 0xFF;
  7. hexChars[j * 2] = hexArray[v >>> 4];
  8. hexChars[j * 2 + 1] = hexArray[v & 0x0F];
  9. }
  10. return new String(hexChars);
  11. }
  12. public static void main(String[] args) {
  13. byte[] bytes = {10, 2, 15, 11};
  14. String s = bytesToHex(bytes);
  15. System.out.println(s);
  16. }
  17. }

The output of the program is same as Example 1.